1
0
mirror of https://github.com/VCMP-SqMod/SqMod.git synced 2025-09-16 09:17:17 +02:00

Major plugin refactor and cleanup.

Switched to POCO library for unified platform/library interface.
Deprecated the external module API. It was creating more problems than solving.
Removed most built-in libraries in favor of system libraries for easier maintenance.
Cleaned and secured code with help from static analyzers.
This commit is contained in:
Sandu Liviu Catalin
2021-01-30 08:51:39 +02:00
parent e0e34b4030
commit 4a6bfc086c
6219 changed files with 1209835 additions and 454916 deletions

View File

@@ -0,0 +1,221 @@
//
// ActiveDispatcherTest.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ActiveDispatcherTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/ActiveDispatcher.h"
#include "Poco/ActiveMethod.h"
#include "Poco/Thread.h"
#include "Poco/Event.h"
#include "Poco/Exception.h"
using Poco::ActiveDispatcher;
using Poco::ActiveMethod;
using Poco::ActiveResult;
using Poco::ActiveStarter;
using Poco::Thread;
using Poco::Event;
using Poco::Exception;
namespace
{
class ActiveObject: public ActiveDispatcher
{
public:
ActiveObject():
testMethod(this, &ActiveObject::testMethodImpl),
testVoid(this, &ActiveObject::testVoidImpl),
testVoidInOut(this, &ActiveObject::testVoidInOutImpl),
testVoidIn(this, &ActiveObject::testVoidInImpl)
{
}
~ActiveObject()
{
}
ActiveMethod<int, int, ActiveObject, ActiveStarter<ActiveDispatcher> > testMethod;
ActiveMethod<void, int, ActiveObject, ActiveStarter<ActiveDispatcher> > testVoid;
ActiveMethod<void, void, ActiveObject, ActiveStarter<ActiveDispatcher> > testVoidInOut;
ActiveMethod<int, void, ActiveObject, ActiveStarter<ActiveDispatcher> > testVoidIn;
void cont()
{
_continue.set();
}
protected:
int testMethodImpl(const int& n)
{
if (n == 100) throw Exception("n == 100");
_continue.wait();
return n;
}
void testVoidImpl(const int& n)
{
if (n == 100) throw Exception("n == 100");
_continue.wait();
}
void testVoidInOutImpl()
{
_continue.wait();
}
int testVoidInImpl()
{
_continue.wait();
return 123;
}
private:
Event _continue;
};
}
ActiveDispatcherTest::ActiveDispatcherTest(const std::string& name): CppUnit::TestCase(name)
{
}
ActiveDispatcherTest::~ActiveDispatcherTest()
{
}
void ActiveDispatcherTest::testWait()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testMethod(123);
assertTrue (!result.available());
activeObj.cont();
result.wait();
assertTrue (result.available());
assertTrue (result.data() == 123);
assertTrue (!result.failed());
}
void ActiveDispatcherTest::testWaitInterval()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testMethod(123);
assertTrue (!result.available());
try
{
result.wait(100);
fail("wait must fail");
}
catch (Exception&)
{
}
activeObj.cont();
result.wait(10000);
assertTrue (result.available());
assertTrue (result.data() == 123);
assertTrue (!result.failed());
}
void ActiveDispatcherTest::testTryWait()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testMethod(123);
assertTrue (!result.available());
assertTrue (!result.tryWait(200));
activeObj.cont();
assertTrue (result.tryWait(10000));
assertTrue (result.available());
assertTrue (result.data() == 123);
assertTrue (!result.failed());
}
void ActiveDispatcherTest::testFailure()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testMethod(100);
result.wait();
assertTrue (result.available());
assertTrue (result.failed());
std::string msg = result.error();
assertTrue (msg == "n == 100");
}
void ActiveDispatcherTest::testVoid()
{
ActiveObject activeObj;
ActiveResult<void> result = activeObj.testVoid(123);
assertTrue (!result.available());
activeObj.cont();
result.wait();
assertTrue (result.available());
assertTrue (!result.failed());
}
void ActiveDispatcherTest::testVoidInOut()
{
ActiveObject activeObj;
ActiveResult<void> result = activeObj.testVoidInOut();
assertTrue (!result.available());
activeObj.cont();
result.wait();
assertTrue (result.available());
assertTrue (!result.failed());
}
void ActiveDispatcherTest::testVoidIn()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testVoidIn();
assertTrue (!result.available());
activeObj.cont();
result.wait();
assertTrue (result.available());
assertTrue (!result.failed());
assertTrue (result.data() == 123);
}
void ActiveDispatcherTest::setUp()
{
}
void ActiveDispatcherTest::tearDown()
{
}
CppUnit::Test* ActiveDispatcherTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActiveDispatcherTest");
CppUnit_addTest(pSuite, ActiveDispatcherTest, testWait);
CppUnit_addTest(pSuite, ActiveDispatcherTest, testWaitInterval);
CppUnit_addTest(pSuite, ActiveDispatcherTest, testTryWait);
CppUnit_addTest(pSuite, ActiveDispatcherTest, testFailure);
CppUnit_addTest(pSuite, ActiveDispatcherTest, testVoid);
CppUnit_addTest(pSuite, ActiveDispatcherTest, testVoidIn);
CppUnit_addTest(pSuite, ActiveDispatcherTest, testVoidInOut);
return pSuite;
}

View File

@@ -0,0 +1,41 @@
//
// ActiveDispatcherTest.h
//
// Definition of the ActiveDispatcherTest class.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ActiveDispatcherTest_INCLUDED
#define ActiveDispatcherTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ActiveDispatcherTest: public CppUnit::TestCase
{
public:
ActiveDispatcherTest(const std::string& name);
~ActiveDispatcherTest();
void testWait();
void testWaitInterval();
void testTryWait();
void testFailure();
void testVoid();
void testVoidIn();
void testVoidInOut();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // ActiveDispatcherTest_INCLUDED

View File

@@ -0,0 +1,261 @@
//
// ActiveMethodTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ActiveMethodTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/ActiveMethod.h"
#include "Poco/Thread.h"
#include "Poco/Event.h"
#include "Poco/Exception.h"
using Poco::ActiveMethod;
using Poco::ActiveResult;
using Poco::Thread;
using Poco::Event;
using Poco::Exception;
namespace
{
class ActiveObject
{
public:
typedef ActiveMethod<int, int, ActiveObject> IntIntType;
typedef ActiveMethod<void, int, ActiveObject> VoidIntType;
typedef ActiveMethod<void, void, ActiveObject> VoidVoidType;
typedef ActiveMethod<int, void, ActiveObject> IntVoidType;
ActiveObject():
testMethod(this, &ActiveObject::testMethodImpl),
testVoid(this,&ActiveObject::testVoidOutImpl),
testVoidInOut(this,&ActiveObject::testVoidInOutImpl),
testVoidIn(this,&ActiveObject::testVoidInImpl)
{
}
~ActiveObject()
{
}
IntIntType testMethod;
VoidIntType testVoid;
VoidVoidType testVoidInOut;
IntVoidType testVoidIn;
void cont()
{
_continue.set();
}
protected:
int testMethodImpl(const int& n)
{
if (n == 100) throw Exception("n == 100");
_continue.wait();
return n;
}
void testVoidOutImpl(const int& n)
{
if (n == 100) throw Exception("n == 100");
_continue.wait();
}
void testVoidInOutImpl()
{
_continue.wait();
}
int testVoidInImpl()
{
_continue.wait();
return 123;
}
private:
Event _continue;
};
}
ActiveMethodTest::ActiveMethodTest(const std::string& name): CppUnit::TestCase(name)
{
}
ActiveMethodTest::~ActiveMethodTest()
{
}
void ActiveMethodTest::testWait()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testMethod(123);
assertTrue (!result.available());
activeObj.cont();
result.wait();
assertTrue (result.available());
assertTrue (result.data() == 123);
assertTrue (!result.failed());
}
void ActiveMethodTest::testCopy()
{
ActiveObject activeObj;
ActiveObject::IntIntType ii = activeObj.testMethod;
ActiveResult<int> rii = ii(123);
assertTrue (!rii.available());
activeObj.cont();
rii.wait();
assertTrue (rii.available());
assertTrue (rii.data() == 123);
assertTrue (!rii.failed());
ActiveObject::VoidIntType vi = activeObj.testVoid;
ActiveResult<void> rvi = vi(123);
assertTrue (!rvi.available());
activeObj.cont();
rvi.wait();
assertTrue (rvi.available());
assertTrue (!rvi.failed());
ActiveObject::VoidVoidType vv = activeObj.testVoidInOut;
ActiveResult<void> rvv = vv();
assertTrue (!rvv.available());
activeObj.cont();
rvv.wait();
assertTrue (rvv.available());
assertTrue (!rvv.failed());
ActiveObject::IntVoidType iv = activeObj.testVoidIn;
ActiveResult<int> riv = iv();
assertTrue (!riv.available());
activeObj.cont();
riv.wait();
assertTrue (riv.available());
assertTrue (riv.data() == 123);
assertTrue (!riv.failed());
}
void ActiveMethodTest::testWaitInterval()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testMethod(123);
assertTrue (!result.available());
try
{
result.wait(100);
fail("wait must fail");
}
catch (Exception&)
{
}
activeObj.cont();
result.wait(10000);
assertTrue (result.available());
assertTrue (result.data() == 123);
assertTrue (!result.failed());
}
void ActiveMethodTest::testTryWait()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testMethod(123);
assertTrue (!result.available());
assertTrue (!result.tryWait(200));
activeObj.cont();
assertTrue (result.tryWait(10000));
assertTrue (result.available());
assertTrue (result.data() == 123);
assertTrue (!result.failed());
}
void ActiveMethodTest::testFailure()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testMethod(100);
result.wait();
assertTrue (result.available());
assertTrue (result.failed());
std::string msg = result.error();
assertTrue (msg == "n == 100");
}
void ActiveMethodTest::testVoidOut()
{
ActiveObject activeObj;
ActiveResult<void> result = activeObj.testVoid(101);
activeObj.cont();
result.wait();
assertTrue (result.available());
assertTrue (!result.failed());
}
void ActiveMethodTest::testVoidInOut()
{
ActiveObject activeObj;
ActiveResult<void> result = activeObj.testVoidInOut();
activeObj.cont();
result.wait();
assertTrue (result.available());
assertTrue (!result.failed());
}
void ActiveMethodTest::testVoidIn()
{
ActiveObject activeObj;
ActiveResult<int> result = activeObj.testVoidIn();
activeObj.cont();
result.wait();
assertTrue (result.available());
assertTrue (!result.failed());
assertTrue (result.data() == 123);
}
void ActiveMethodTest::setUp()
{
}
void ActiveMethodTest::tearDown()
{
}
CppUnit::Test* ActiveMethodTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActiveMethodTest");
CppUnit_addTest(pSuite, ActiveMethodTest, testWait);
CppUnit_addTest(pSuite, ActiveMethodTest, testCopy);
CppUnit_addTest(pSuite, ActiveMethodTest, testWaitInterval);
CppUnit_addTest(pSuite, ActiveMethodTest, testTryWait);
CppUnit_addTest(pSuite, ActiveMethodTest, testFailure);
CppUnit_addTest(pSuite, ActiveMethodTest, testVoidOut);
CppUnit_addTest(pSuite, ActiveMethodTest, testVoidIn);
CppUnit_addTest(pSuite, ActiveMethodTest, testVoidInOut);
return pSuite;
}

View File

@@ -0,0 +1,45 @@
//
// ActiveMethodTest.h
//
// Definition of the ActiveMethodTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ActiveMethodTest_INCLUDED
#define ActiveMethodTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ActiveMethodTest: public CppUnit::TestCase
{
public:
ActiveMethodTest(const std::string& name);
~ActiveMethodTest();
void testWait();
void testCopy();
void testWaitInterval();
void testTryWait();
void testFailure();
void testVoidOut();
void testVoidInOut();
void testVoidIn();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // ActiveMethodTest_INCLUDED

View File

@@ -0,0 +1,102 @@
//
// ActivityTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ActivityTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Activity.h"
#include "Poco/Thread.h"
using Poco::Activity;
using Poco::Thread;
namespace
{
class ActiveObject
{
public:
ActiveObject():
_activity(this, &ActiveObject::run),
_count(0)
{
}
~ActiveObject()
{
}
Activity<ActiveObject>& activity()
{
return _activity;
}
Poco::UInt64 count() const
{
return _count;
}
protected:
void run()
{
while (!_activity.isStopped())
++_count;
}
private:
Activity<ActiveObject> _activity;
Poco::UInt64 _count;
};
}
ActivityTest::ActivityTest(const std::string& name): CppUnit::TestCase(name)
{
}
ActivityTest::~ActivityTest()
{
}
void ActivityTest::testActivity()
{
ActiveObject activeObj;
assertTrue (activeObj.activity().isStopped());
activeObj.activity().start();
assertTrue (!activeObj.activity().isStopped());
Thread::sleep(1000);
assertTrue (activeObj.activity().isRunning());
activeObj.activity().stop();
activeObj.activity().wait();
assertTrue (activeObj.count() > 0);
}
void ActivityTest::setUp()
{
}
void ActivityTest::tearDown()
{
}
CppUnit::Test* ActivityTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActivityTest");
CppUnit_addTest(pSuite, ActivityTest, testActivity);
return pSuite;
}

View File

@@ -0,0 +1,38 @@
//
// ActivityTest.h
//
// Definition of the ActivityTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ActivityTest_INCLUDED
#define ActivityTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ActivityTest: public CppUnit::TestCase
{
public:
ActivityTest(const std::string& name);
~ActivityTest();
void testActivity();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // ActivityTest_INCLUDED

View File

@@ -0,0 +1,301 @@
//
// AnyTest.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "AnyTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Exception.h"
#include "Poco/Any.h"
#include "Poco/Bugcheck.h"
#include <vector>
#if defined(_MSC_VER) && _MSC_VER < 1400
#pragma warning(disable:4800)//forcing value to bool 'true' or 'false'
#endif
using namespace Poco;
class SomeClass
{
public:
int i;
std::string str;
SomeClass(int h, std::string s): i (h), str(s)
{
};
bool operator==(const SomeClass& other) const
{
return i == other.i && str == other.str;
}
};
AnyTest::AnyTest(const std::string& name): CppUnit::TestCase(name)
{
}
AnyTest::~AnyTest()
{
}
void AnyTest::testDefaultCtor()
{
const Any value;
assertTrue (value.empty());
assertTrue (0 == AnyCast<int>(&value));
assertTrue (value.type() == typeid(void));
}
void AnyTest::testConvertingCtor()
{
std::string text = "test message";
Any value = text;
assertTrue (!value.empty());
assertTrue (value.type() == typeid(std::string));
assertTrue (0 == AnyCast<int>(&value));
assertTrue (0 != AnyCast<std::string>(&value));
assertTrue (AnyCast<std::string>(value) == text);
assertTrue (AnyCast<std::string>(&value) != &text);
}
void AnyTest::testCopyCtor()
{
std::string text = "test message";
Any original = text, copy = original;
assertTrue (!copy.empty());
assertTrue (original.type() == copy.type());
assertTrue (AnyCast<std::string>(original) == AnyCast<std::string>(copy));
assertTrue (text == AnyCast<std::string>(copy));
assertTrue (AnyCast<std::string>(&original) != AnyCast<std::string>(&copy));
}
void AnyTest::testCopyAssign()
{
std::string text = "test message";
Any original = text, copy;
Any* assignResult = &(copy = original);
assertTrue (!copy.empty());
assertTrue (original.type() == copy.type());
assertTrue (AnyCast<std::string>(original) == AnyCast<std::string>(copy));
assertTrue (text == AnyCast<std::string>(copy));
assertTrue (AnyCast<std::string>(&original) != AnyCast<std::string>(&copy));
assertTrue (assignResult == &copy);
// test self assignment
Any& ref = original;
original = ref;
assertTrue (AnyCast<std::string>(original) == AnyCast<std::string>(copy));
original = original;
assertTrue (AnyCast<std::string>(original) == AnyCast<std::string>(copy));
}
void AnyTest::testConvertingAssign()
{
std::string text = "test message";
Any value;
Any* assignResult = &(value = text);
assertTrue (!value.empty());
assertTrue (value.type() == typeid(std::string));
assertTrue (0 == AnyCast<int>(&value));
assertTrue (0 != AnyCast<std::string>(&value));
assertTrue (AnyCast<std::string>(value) == text);
assertTrue (AnyCast<std::string>(&value) != &text);
assertTrue (assignResult == &value);
}
void AnyTest::testCastToReference()
{
Any a(137);
const Any b(a);
int& ra = AnyCast<int &>(a);
int const& ra_c = AnyCast<int const &>(a);
int volatile& ra_v = AnyCast<int volatile &>(a);
int const volatile& ra_cv = AnyCast<int const volatile&>(a);
// cv references to same obj
assertTrue (&ra == &ra_c && &ra == &ra_v && &ra == &ra_cv);
int const & rb_c = AnyCast<int const &>(b);
int const volatile & rb_cv = AnyCast<int const volatile &>(b);
assertTrue (&rb_c == &rb_cv); // cv references to copied const obj
assertTrue (&ra != &rb_c); // copies hold different objects
++ra;
int incremented = AnyCast<int>(a);
assertTrue (incremented == 138); // increment by reference changes value
try
{
AnyCast<char &>(a);
failmsg ("AnyCast to incorrect reference type");
}
catch (BadCastException&) { }
try
{
AnyCast<const char &>(b),
failmsg ("AnyCast to incorrect const reference type");
}
catch (BadCastException&) { }
}
void AnyTest::testBadCast()
{
std::string text = "test message";
Any value = text;
try
{
AnyCast<const char *>(value);
fail ("must throw");
}
catch (BadCastException&) { }
}
void AnyTest::testSwap()
{
std::string text = "test message";
Any original = text, swapped;
std::string* originalPtr = AnyCast<std::string>(&original);
Any* swapResult = &original.swap(swapped);
assertTrue (original.empty());
assertTrue (!swapped.empty());
assertTrue (swapped.type() == typeid(std::string));
assertTrue (text == AnyCast<std::string>(swapped));
assertTrue (0 != originalPtr);
#ifdef POCO_NO_SOO // pointers only match when heap-allocated
assertTrue (originalPtr == AnyCast<std::string>(&swapped));
#endif
assertTrue (swapResult == &original);
}
void AnyTest::testEmptyCopy()
{
const Any null;
Any copied = null, assigned;
assigned = null;
assertTrue (null.empty());
assertTrue (copied.empty());
assertTrue (assigned.empty());
}
void AnyTest::testInt()
{
Any e;
assertTrue (e.empty());
Any a = 13;
assertTrue (a.type() == typeid(int));
int* i = AnyCast<int>(&a);
assertTrue (*i == 13);
Any b = a;
assertTrue (b.type() == typeid(int));
int *cpyI = AnyCast<int>(&b);
assertTrue (*cpyI == *i);
*cpyI = 20;
assertTrue (*cpyI != *i);
std::string* s = AnyCast<std::string>(&a);
assertTrue (s == NULL);
int POCO_UNUSED tmp = AnyCast<int>(a);
const Any c = a;
tmp = AnyCast<int>(a);
}
void AnyTest::testComplexType()
{
SomeClass str(13,std::string("hello"));
Any a = str;
Any b = a;
assertTrue (a.type() == typeid(SomeClass));
assertTrue (b.type() == typeid(SomeClass));
SomeClass str2 = AnyCast<SomeClass>(a);
assertTrue (str == str2);
const SomeClass& strCRef = RefAnyCast<SomeClass>(a);
assertTrue (str == strCRef);
SomeClass& strRef = RefAnyCast<SomeClass>(a);
assertTrue (str == strRef);
}
void AnyTest::testVector()
{
std::vector<int> tmp;
tmp.push_back(1);
tmp.push_back(2);
tmp.push_back(3);
Any a = tmp;
assertTrue (a.type() == typeid(std::vector<int>));
std::vector<int> tmp2 = AnyCast<std::vector<int> >(a);
assertTrue (tmp2.size() == 3);
const std::vector<int>& vecCRef = RefAnyCast<std::vector<int> >(a);
std::vector<int>& vecRef = RefAnyCast<std::vector<int> >(a);
assertTrue (vecRef[0] == 1);
assertTrue (vecRef[1] == 2);
assertTrue (vecRef[2] == 3);
vecRef[0] = 0;
assertTrue (vecRef[0] == vecCRef[0]);
}
void AnyTest::setUp()
{
}
void AnyTest::tearDown()
{
}
CppUnit::Test* AnyTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("AnyTest");
CppUnit_addTest(pSuite, AnyTest, testConvertingCtor);
CppUnit_addTest(pSuite, AnyTest, testDefaultCtor);
CppUnit_addTest(pSuite, AnyTest, testCopyCtor);
CppUnit_addTest(pSuite, AnyTest, testCopyAssign);
CppUnit_addTest(pSuite, AnyTest, testConvertingAssign);
CppUnit_addTest(pSuite, AnyTest, testBadCast);
CppUnit_addTest(pSuite, AnyTest, testSwap);
CppUnit_addTest(pSuite, AnyTest, testEmptyCopy);
CppUnit_addTest(pSuite, AnyTest, testCastToReference);
CppUnit_addTest(pSuite, AnyTest, testInt);
CppUnit_addTest(pSuite, AnyTest, testComplexType);
CppUnit_addTest(pSuite, AnyTest, testVector);
return pSuite;
}

View File

@@ -0,0 +1,46 @@
//
// AnyTest.h
//
// Tests for Any types
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef AnyTest_INCLUDED
#define AnyTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class AnyTest: public CppUnit::TestCase
{
public:
AnyTest(const std::string& name);
~AnyTest();
void testConvertingCtor();
void testDefaultCtor();
void testCopyCtor();
void testCopyAssign();
void testConvertingAssign();
void testBadCast();
void testSwap();
void testEmptyCopy();
void testCastToReference();
void testInt();
void testComplexType();
void testVector();
void setUp();
void tearDown();
static CppUnit::Test* suite();
};
#endif // AnyTest_INCLUDED

View File

@@ -0,0 +1,231 @@
//
// ArrayTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ArrayTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Array.h"
#include <vector>
#include <algorithm>
#include <functional>
ArrayTest::ArrayTest(const std::string& name): CppUnit::TestCase(name)
{
}
ArrayTest::~ArrayTest()
{
}
struct Element
{
int _data;
};
void ArrayTest::testConstruction()
{
// fundamental type
typedef Poco::Array<float,6> FloatArray;
FloatArray a = { { 42.f } };
for (unsigned i=1; i<a.size(); ++i) {
a[i] = a[i-1]+1.f;
}
// copy constructor and assignment operator
FloatArray b(a);
FloatArray c;
c = a;
assertTrue (a==b && a==c);
typedef Poco::Array<double,6> DArray;
typedef Poco::Array<int,6> IArray;
IArray ia = {{1, 2, 3, 4, 5, 6 }};
DArray da;
da = ia;
da.assign(42);
// user-defined type
typedef Poco::Array<Element,10> ElementArray;
ElementArray g;
for (unsigned i=0; i<g.size(); ++i) {
g[i]._data = i;
}
for (unsigned i=0; i<g.size(); ++i) {
assertTrue (g[i]._data == i);
}
}
void ArrayTest::testOperations()
{
const int SIZE = 6;
typedef Poco::Array<int,SIZE> Array;
Array a = { { 1 } };
// use some common STL container operations
assertTrue (a.size() == SIZE);
assertTrue (a.max_size() == SIZE);
assertTrue (a.empty() == false);
assertTrue (a.front() == a[0]);
assertTrue (a.back() == a[a.size()-1]);
//assertTrue (a.data() == &a[0]);
// assign
a.assign(100);
for(int i = 0; i<a.size(); i++){
assertTrue (a[i] == 100);
}
// swap
Array b;
b.assign(10);
for(int i=0; i<SIZE; i++){
assertTrue (a[i] == 100);
assertTrue (b[i] == 10);
}
a.swap(b);
for(int i=0; i<SIZE; i++){
assertTrue (a[i] == 10);
assertTrue (b[i] == 100);
}
}
void ArrayTest::testContainer()
{
const int SIZE = 2;
typedef Poco::Array<int,SIZE> Array;
Array a = {{1, 2}};
assertTrue (a[0] == 1);
assertTrue (a[1] == 2);
typedef std::vector<Array> ArrayVec;
ArrayVec container;
container.push_back(a);
container.push_back(a);
assertTrue (container[0][0] == 1);
assertTrue (container[0][1] == 2);
assertTrue (container[1][0] == 1);
assertTrue (container[1][1] == 2);
}
void ArrayTest::testIterator()
{
// create array of four seasons
Poco::Array<std::string,4> seasons = {
{ "spring", "summer", "autumn", "winter" }
};
// copy and change order
Poco::Array<std::string,4> org = seasons;
for (size_t i=seasons.size()-1; i>0; --i) {
swap(seasons.at(i),seasons.at((i+1)%seasons.size()));
}
// try swap()
swap(seasons,org);
// try reverse iterators
for (Poco::Array<std::string,4>::reverse_iterator pos
=seasons.rbegin(); pos<seasons.rend(); ++pos) {
}
}
void ArrayTest::testAlgorithm()
{
// create and initialize array
const int SIZE = 10;
typedef Poco::Array<int,SIZE> IArray;
IArray a = { { 1, 2, 3, 4, 5 } };
IArray b(a);
// modify elements directly
for (unsigned i=0; i<b.size(); ++i) {
++b[i];
}
// try iterators
for (IArray::iterator pos =b.begin(); pos<b.end(); ++pos) {
--(*pos);
}
for (unsigned i=0; i<a.size(); ++i) {
assertTrue (a[i] == b[i]);
}
// change order using an STL algorithm
std::reverse(a.begin(),a.end());
for (unsigned i=0; i<a.size(); ++i) {
assertTrue (a[SIZE-i-1] == b[i]);
}
std::reverse(a.begin(),a.end());
// negate elements using STL framework
std::transform( a.begin(),a.end(), // source
a.begin(), // destination
std::negate<int>()); // operation
for (unsigned i=0; i<a.size(); ++i) {
assertTrue (a[i] == -b[i]);
}
}
void ArrayTest::testMultiLevelArray()
{
const int SIZE = 2;
typedef Poco::Array<int,SIZE> IArray;
typedef Poco::Array<IArray,SIZE> MultiArray;
MultiArray a;
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
MultiArray b = a;
assertTrue (b[0][0] == 1);
assertTrue (b[0][1] == 2);
assertTrue (b[1][0] == 3);
assertTrue (b[1][1] == 4);
}
void ArrayTest::setUp()
{
}
void ArrayTest::tearDown()
{
}
CppUnit::Test* ArrayTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ArrayTest");
CppUnit_addTest(pSuite, ArrayTest, testConstruction);
CppUnit_addTest(pSuite, ArrayTest, testOperations);
CppUnit_addTest(pSuite, ArrayTest, testContainer);
CppUnit_addTest(pSuite, ArrayTest, testIterator);
CppUnit_addTest(pSuite, ArrayTest, testAlgorithm);
CppUnit_addTest(pSuite, ArrayTest, testMultiLevelArray);
return pSuite;
}

View File

@@ -0,0 +1,44 @@
//
// ArrayTest.h
//
// Definition of the ArrayTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ArrayTest_INCLUDED
#define ArrayTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ArrayTest: public CppUnit::TestCase
{
public:
ArrayTest(const std::string& name);
~ArrayTest();
void testConstruction();
void testOperations();
void testContainer();
void testIterator();
void testAlgorithm();
void testMultiLevelArray();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // ArrayTest_INCLUDED

View File

@@ -0,0 +1,220 @@
//
// AutoPtrTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "AutoPtrTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/AutoPtr.h"
#include "Poco/Exception.h"
using Poco::AutoPtr;
using Poco::makeAuto;
using Poco::NullPointerException;
namespace
{
class TestObj
{
public:
TestObj(): _rc(1)
{
++_count;
}
explicit TestObj(int value): _rc(1)
{
}
TestObj(int value1, const std::string& value2): _rc(1)
{
}
void duplicate()
{
++_rc;
}
void release()
{
if (--_rc == 0)
delete this;
}
int rc() const
{
return _rc;
}
static int count()
{
return _count;
}
protected:
~TestObj()
{
--_count;
}
private:
int _rc;
static int _count;
};
int TestObj::_count = 0;
}
AutoPtrTest::AutoPtrTest(const std::string& name): CppUnit::TestCase(name)
{
}
AutoPtrTest::~AutoPtrTest()
{
}
void AutoPtrTest::testAutoPtr()
{
{
AutoPtr<TestObj> ptr = new TestObj;
assertTrue (ptr->rc() == 1);
AutoPtr<TestObj> ptr2 = ptr;
assertTrue (ptr->rc() == 2);
ptr2 = new TestObj;
assertTrue (ptr->rc() == 1);
AutoPtr<TestObj> ptr3;
ptr3 = ptr2;
assertTrue (ptr2->rc() == 2);
ptr3 = new TestObj;
assertTrue (ptr2->rc() == 1);
ptr3 = ptr2;
assertTrue (ptr2->rc() == 2);
assertTrue (TestObj::count() > 0);
AutoPtr<TestObj> ptr4 = std::move(ptr);
assertTrue (ptr4->rc() == 1);
assertTrue (ptr.isNull());
ptr3 = std::move(ptr4);
assertTrue (ptr4.isNull());
assertTrue (ptr3->rc() == 1);
}
assertTrue (TestObj::count() == 0);
}
void AutoPtrTest::testOps()
{
AutoPtr<TestObj> ptr1;
assertNull(ptr1.get());
TestObj* pTO1 = new TestObj;
TestObj* pTO2 = new TestObj;
if (pTO2 < pTO1)
{
TestObj* pTmp = pTO1;
pTO1 = pTO2;
pTO2 = pTmp;
}
assertTrue (pTO1 < pTO2);
ptr1 = pTO1;
AutoPtr<TestObj> ptr2 = pTO2;
AutoPtr<TestObj> ptr3 = ptr1;
AutoPtr<TestObj> ptr4;
assertTrue (ptr1.get() == pTO1);
assertTrue (ptr1 == pTO1);
assertTrue (ptr2.get() == pTO2);
assertTrue (ptr2 == pTO2);
assertTrue (ptr3.get() == pTO1);
assertTrue (ptr3 == pTO1);
assertTrue (ptr1 == pTO1);
assertTrue (ptr1 != pTO2);
assertTrue (ptr1 < pTO2);
assertTrue (ptr1 <= pTO2);
assertTrue (ptr2 > pTO1);
assertTrue (ptr2 >= pTO1);
assertTrue (ptr1 == ptr3);
assertTrue (ptr1 != ptr2);
assertTrue (ptr1 < ptr2);
assertTrue (ptr1 <= ptr2);
assertTrue (ptr2 > ptr1);
assertTrue (ptr2 >= ptr1);
ptr1 = pTO1;
ptr2 = pTO2;
ptr1.swap(ptr2);
assertTrue (ptr2.get() == pTO1);
assertTrue (ptr1.get() == pTO2);
try
{
assertTrue (ptr4->rc() > 0);
fail ("must throw NullPointerException");
}
catch (NullPointerException&)
{
}
assertTrue (!(ptr4 == ptr1));
assertTrue (!(ptr4 == ptr2));
assertTrue (ptr4 != ptr1);
assertTrue (ptr4 != ptr2);
ptr4 = ptr2;
assertTrue (ptr4 == ptr2);
assertTrue (!(ptr4 != ptr2));
assertTrue (!(!ptr1));
ptr1 = 0;
assertTrue (!ptr1);
assertTrue (ptr1 == nullptr);
assertTrue (ptr2 != nullptr);
}
void AutoPtrTest::testMakeAuto()
{
AutoPtr<TestObj> ptr = makeAuto<TestObj>();
assertTrue (ptr->rc() == 1);
ptr = makeAuto<TestObj>(42);
assertTrue (ptr->rc() == 1);
ptr = makeAuto<TestObj>(42, "fortytwo");
assertTrue (ptr->rc() == 1);
}
void AutoPtrTest::setUp()
{
}
void AutoPtrTest::tearDown()
{
}
CppUnit::Test* AutoPtrTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("AutoPtrTest");
CppUnit_addTest(pSuite, AutoPtrTest, testAutoPtr);
CppUnit_addTest(pSuite, AutoPtrTest, testOps);
CppUnit_addTest(pSuite, AutoPtrTest, testMakeAuto);
return pSuite;
}

View File

@@ -0,0 +1,40 @@
//
// AutoPtrTest.h
//
// Definition of the AutoPtrTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef AutoPtrTest_INCLUDED
#define AutoPtrTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class AutoPtrTest: public CppUnit::TestCase
{
public:
AutoPtrTest(const std::string& name);
~AutoPtrTest();
void testAutoPtr();
void testOps();
void testMakeAuto();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // AutoPtrTest_INCLUDED

View File

@@ -0,0 +1,104 @@
//
// AutoReleasePoolTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "AutoReleasePoolTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/AutoReleasePool.h"
using Poco::AutoReleasePool;
namespace
{
class TestObj
{
public:
TestObj(): _rc(1)
{
++_count;
}
void duplicate()
{
++_rc;
}
void release()
{
if (--_rc == 0)
delete this;
}
int rc() const
{
return _rc;
}
static int count()
{
return _count;
}
protected:
~TestObj()
{
--_count;
}
private:
int _rc;
static int _count;
};
int TestObj::_count = 0;
}
AutoReleasePoolTest::AutoReleasePoolTest(const std::string& name): CppUnit::TestCase(name)
{
}
AutoReleasePoolTest::~AutoReleasePoolTest()
{
}
void AutoReleasePoolTest::testAutoReleasePool()
{
AutoReleasePool<TestObj> arp;
arp.add(new TestObj);
arp.add(new TestObj);
assertTrue (TestObj::count() == 2);
arp.release();
assertTrue (TestObj::count() == 0);
}
void AutoReleasePoolTest::setUp()
{
}
void AutoReleasePoolTest::tearDown()
{
}
CppUnit::Test* AutoReleasePoolTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("AutoReleasePoolTest");
CppUnit_addTest(pSuite, AutoReleasePoolTest, testAutoReleasePool);
return pSuite;
}

View File

@@ -0,0 +1,38 @@
//
// AutoReleasePoolTest.h
//
// Definition of the AutoReleasePoolTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef AutoReleasePoolTest_INCLUDED
#define AutoReleasePoolTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class AutoReleasePoolTest: public CppUnit::TestCase
{
public:
AutoReleasePoolTest(const std::string& name);
~AutoReleasePoolTest();
void testAutoReleasePool();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // AutoReleasePoolTest_INCLUDED

View File

@@ -0,0 +1,182 @@
//
// Base32Test.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Base32Test.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Base32Encoder.h"
#include "Poco/Base32Decoder.h"
#include "Poco/Exception.h"
#include <sstream>
using Poco::Base32Encoder;
using Poco::Base32Decoder;
using Poco::DataFormatException;
Base32Test::Base32Test(const std::string& name): CppUnit::TestCase(name)
{
}
Base32Test::~Base32Test()
{
}
void Base32Test::testEncoder()
{
{
std::ostringstream str;
Base32Encoder encoder(str);
encoder << std::string("\00\01\02\03\04\05", 6);
encoder.close();
assertTrue (str.str() == "AAAQEAYEAU======");
}
{
std::ostringstream str;
Base32Encoder encoder(str);
encoder << std::string("\00\01\02\03", 4);
encoder.close();
assertTrue (str.str() == "AAAQEAY=");
}
{
std::ostringstream str;
Base32Encoder encoder(str, false);
encoder << "ABCDEF";
encoder.close();
assertTrue (str.str() == "IFBEGRCFIY");
}
{
std::ostringstream str;
Base32Encoder encoder(str);
encoder << "ABCDEF";
encoder.close();
assertTrue (str.str() == "IFBEGRCFIY======");
}
{
std::ostringstream str;
Base32Encoder encoder(str);
encoder << "ABCDE";
encoder.close();
assertTrue (str.str() == "IFBEGRCF");
}
}
void Base32Test::testDecoder()
{
{
std::istringstream istr("AAAQEAYEAU======");
Base32Decoder decoder(istr);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == 4);
assertTrue (decoder.good() && decoder.get() == 5);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("AAAQEAYE");
Base32Decoder decoder(istr);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == 4);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("AAAQEAY=");
Base32Decoder decoder(istr);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("IFBEGRCFIY======");
Base32Decoder decoder(istr);
std::string s;
decoder >> s;
assertTrue (s == "ABCDEF");
assertTrue (decoder.eof());
assertTrue (!decoder.fail());
}
{
std::istringstream istr("QUJD#REVG");
Base32Decoder decoder(istr);
std::string s;
try
{
decoder >> s;
assertTrue (decoder.bad());
}
catch (DataFormatException&)
{
}
assertTrue (!decoder.eof());
}
}
void Base32Test::testEncodeDecode()
{
{
std::stringstream str;
Base32Encoder encoder(str);
encoder << "The quick brown fox ";
encoder << "jumped over the lazy dog.";
encoder.close();
Base32Decoder decoder(str);
std::string s;
int c = decoder.get();
while (c != -1) { s += char(c); c = decoder.get(); }
assertTrue (s == "The quick brown fox jumped over the lazy dog.");
}
{
std::string src;
for (int i = 0; i < 255; ++i) src += char(i);
std::stringstream str;
Base32Encoder encoder(str);
encoder.write(src.data(), (std::streamsize) src.size());
encoder.close();
Base32Decoder decoder(str);
std::string s;
int c = decoder.get();
while (c != -1) { s += char(c); c = decoder.get(); }
assertTrue (s == src);
}
}
void Base32Test::setUp()
{
}
void Base32Test::tearDown()
{
}
CppUnit::Test* Base32Test::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("Base32Test");
CppUnit_addTest(pSuite, Base32Test, testEncoder);
CppUnit_addTest(pSuite, Base32Test, testDecoder);
CppUnit_addTest(pSuite, Base32Test, testEncodeDecode);
return pSuite;
}

View File

@@ -0,0 +1,40 @@
//
// Base32Test.h
//
// Definition of the Base32Test class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Base32Test_INCLUDED
#define Base32Test_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class Base32Test: public CppUnit::TestCase
{
public:
Base32Test(const std::string& name);
~Base32Test();
void testEncoder();
void testDecoder();
void testEncodeDecode();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // Base32Test_INCLUDED

View File

@@ -0,0 +1,369 @@
//
// Base64Test.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Base64Test.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Base64Encoder.h"
#include "Poco/Base64Decoder.h"
#include "Poco/Exception.h"
#include <sstream>
using Poco::Base64Encoder;
using Poco::Base64Decoder;
using Poco::DataFormatException;
Base64Test::Base64Test(const std::string& name): CppUnit::TestCase(name)
{
}
Base64Test::~Base64Test()
{
}
void Base64Test::testEncoder()
{
{
std::ostringstream str;
Base64Encoder encoder(str);
encoder << std::string("\00\01\02\03\04\05", 6);
encoder.close();
assertTrue (str.str() == "AAECAwQF");
}
{
std::ostringstream str;
Base64Encoder encoder(str);
encoder << std::string("\00\01\02\03", 4);
encoder.close();
assertTrue (str.str() == "AAECAw==");
}
{
std::ostringstream str;
Base64Encoder encoder(str);
encoder << "ABCDEF";
encoder.close();
assertTrue (str.str() == "QUJDREVG");
}
{
std::ostringstream str;
Base64Encoder encoder(str);
encoder << "!@#$%^&*()_~<>";
encoder.close();
assertTrue (str.str() == "IUAjJCVeJiooKV9+PD4=");
}
}
void Base64Test::testEncoderURL()
{
{
std::ostringstream str;
Base64Encoder encoder(str, Poco::BASE64_URL_ENCODING);
encoder << std::string("\00\01\02\03\04\05", 6);
encoder.close();
assertTrue (str.str() == "AAECAwQF");
}
{
std::ostringstream str;
Base64Encoder encoder(str, Poco::BASE64_URL_ENCODING);
encoder << std::string("\00\01\02\03", 4);
encoder.close();
assertTrue (str.str() == "AAECAw==");
}
{
std::ostringstream str;
Base64Encoder encoder(str, Poco::BASE64_URL_ENCODING);
encoder << "ABCDEF";
encoder.close();
assertTrue (str.str() == "QUJDREVG");
}
{
std::ostringstream str;
Base64Encoder encoder(str, Poco::BASE64_URL_ENCODING);
encoder << "!@#$%^&*()_~<>";
encoder.close();
assertTrue (str.str() == "IUAjJCVeJiooKV9-PD4=");
}
}
void Base64Test::testEncoderNoPadding()
{
{
std::ostringstream str;
Base64Encoder encoder(str, Poco::BASE64_URL_ENCODING | Poco::BASE64_NO_PADDING);
encoder << std::string("\00\01\02\03\04\05", 6);
encoder.close();
assertTrue (str.str() == "AAECAwQF");
}
{
std::ostringstream str;
Base64Encoder encoder(str, Poco::BASE64_URL_ENCODING | Poco::BASE64_NO_PADDING);
encoder << std::string("\00\01\02\03", 4);
encoder.close();
assertTrue (str.str() == "AAECAw");
}
{
std::ostringstream str;
Base64Encoder encoder(str, Poco::BASE64_URL_ENCODING | Poco::BASE64_NO_PADDING);
encoder << "ABCDEF";
encoder.close();
assertTrue (str.str() == "QUJDREVG");
}
{
std::ostringstream str;
Base64Encoder encoder(str, Poco::BASE64_URL_ENCODING | Poco::BASE64_NO_PADDING);
encoder << "!@#$%^&*()_~<>";
encoder.close();
assertTrue (str.str() == "IUAjJCVeJiooKV9-PD4");
}
}
void Base64Test::testDecoder()
{
{
std::istringstream istr("AAECAwQF");
Base64Decoder decoder(istr);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == 4);
assertTrue (decoder.good() && decoder.get() == 5);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("AAECAwQ=");
Base64Decoder decoder(istr);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == 4);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("AAECAw==");
Base64Decoder decoder(istr);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("QUJDREVG");
Base64Decoder decoder(istr);
std::string s;
decoder >> s;
assertTrue (s == "ABCDEF");
assertTrue (decoder.eof());
assertTrue (!decoder.fail());
}
{
std::istringstream istr("QUJ\r\nDRE\r\nVG");
Base64Decoder decoder(istr);
std::string s;
decoder >> s;
assertTrue (s == "ABCDEF");
assertTrue (decoder.eof());
assertTrue (!decoder.fail());
}
{
std::istringstream istr("QUJD#REVG");
Base64Decoder decoder(istr);
std::string s;
try
{
decoder >> s;
assertTrue (decoder.bad());
}
catch (DataFormatException&)
{
}
assertTrue (!decoder.eof());
}
}
void Base64Test::testDecoderURL()
{
{
std::istringstream istr("AAECAwQF");
Base64Decoder decoder(istr, Poco::BASE64_URL_ENCODING);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == 4);
assertTrue (decoder.good() && decoder.get() == 5);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("AAECAwQ=");
Base64Decoder decoder(istr, Poco::BASE64_URL_ENCODING);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == 4);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("AAECAw==");
Base64Decoder decoder(istr, Poco::BASE64_URL_ENCODING);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("QUJDREVG");
Base64Decoder decoder(istr, Poco::BASE64_URL_ENCODING);
std::string s;
decoder >> s;
assertTrue (s == "ABCDEF");
assertTrue (decoder.eof());
assertTrue (!decoder.fail());
}
{
std::istringstream istr("QUJ\r\nDRE\r\nVG");
Base64Decoder decoder(istr, Poco::BASE64_URL_ENCODING);
try
{
std::string s;
decoder >> s;
assertTrue (decoder.bad());
}
catch (DataFormatException&)
{
}
}
{
std::istringstream istr("QUJD#REVG");
Base64Decoder decoder(istr, Poco::BASE64_URL_ENCODING);
std::string s;
try
{
decoder >> s;
assertTrue (decoder.bad());
}
catch (DataFormatException&)
{
}
assertTrue (!decoder.eof());
}
{
std::istringstream istr("IUAjJCVeJiooKV9-PD4=");
Base64Decoder decoder(istr, Poco::BASE64_URL_ENCODING);
std::string s;
decoder >> s;
assertTrue (s == "!@#$%^&*()_~<>");
assertTrue (decoder.eof());
assertTrue (!decoder.fail());
}
}
void Base64Test::testDecoderNoPadding()
{
{
std::istringstream istr("AAECAwQF");
Base64Decoder decoder(istr, Poco::BASE64_NO_PADDING);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == 4);
assertTrue (decoder.good() && decoder.get() == 5);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("AAECAwQ");
Base64Decoder decoder(istr, Poco::BASE64_NO_PADDING);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == 4);
assertTrue (decoder.good() && decoder.get() == -1);
}
{
std::istringstream istr("AAECAw");
Base64Decoder decoder(istr, Poco::BASE64_NO_PADDING);
assertTrue (decoder.good() && decoder.get() == 0);
assertTrue (decoder.good() && decoder.get() == 1);
assertTrue (decoder.good() && decoder.get() == 2);
assertTrue (decoder.good() && decoder.get() == 3);
assertTrue (decoder.good() && decoder.get() == -1);
}
}
void Base64Test::testEncodeDecode()
{
{
std::stringstream str;
Base64Encoder encoder(str);
encoder << "The quick brown fox ";
encoder << "jumped over the lazy dog.";
encoder.close();
Base64Decoder decoder(str);
std::string s;
int c = decoder.get();
while (c != -1) { s += char(c); c = decoder.get(); }
assertTrue (s == "The quick brown fox jumped over the lazy dog.");
}
{
std::string src;
for (int i = 0; i < 255; ++i) src += char(i);
std::stringstream str;
Base64Encoder encoder(str);
encoder.write(src.data(), (std::streamsize) src.size());
encoder.close();
Base64Decoder decoder(str);
std::string s;
int c = decoder.get();
while (c != -1) { s += char(c); c = decoder.get(); }
assertTrue (s == src);
}
}
void Base64Test::setUp()
{
}
void Base64Test::tearDown()
{
}
CppUnit::Test* Base64Test::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("Base64Test");
CppUnit_addTest(pSuite, Base64Test, testEncoder);
CppUnit_addTest(pSuite, Base64Test, testEncoderURL);
CppUnit_addTest(pSuite, Base64Test, testEncoderNoPadding);
CppUnit_addTest(pSuite, Base64Test, testDecoder);
CppUnit_addTest(pSuite, Base64Test, testDecoderURL);
CppUnit_addTest(pSuite, Base64Test, testDecoderNoPadding);
CppUnit_addTest(pSuite, Base64Test, testEncodeDecode);
return pSuite;
}

View File

@@ -0,0 +1,44 @@
//
// Base64Test.h
//
// Definition of the Base64Test class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Base64Test_INCLUDED
#define Base64Test_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class Base64Test: public CppUnit::TestCase
{
public:
Base64Test(const std::string& name);
~Base64Test();
void testEncoder();
void testEncoderURL();
void testEncoderNoPadding();
void testDecoder();
void testDecoderURL();
void testDecoderNoPadding();
void testEncodeDecode();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // Base64Test_INCLUDED

View File

@@ -0,0 +1,438 @@
//
// BasicEventTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "BasicEventTest.h"
#include "DummyDelegate.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Expire.h"
#include "Poco/Delegate.h"
#include "Poco/FunctionDelegate.h"
#include "Poco/Thread.h"
#include "Poco/Exception.h"
using namespace Poco;
#define LARGEINC 100
BasicEventTest::BasicEventTest(const std::string& name): CppUnit::TestCase(name)
{
}
BasicEventTest::~BasicEventTest()
{
}
void BasicEventTest::testNoDelegate()
{
int tmp = 0;
EventArgs args;
assertTrue (_count == 0);
assertTrue (Void.empty());
Void.notify(this);
assertTrue (_count == 0);
Void += delegate(this, &BasicEventTest::onVoid);
assertTrue (!Void.empty());
Void -= delegate(this, &BasicEventTest::onVoid);
assertTrue (Void.empty());
Void.notify(this);
assertTrue (_count == 0);
assertTrue (Simple.empty());
Simple.notify(this, tmp);
assertTrue (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple);
assertTrue (!Simple.empty());
Simple -= delegate(this, &BasicEventTest::onSimple);
assertTrue (Simple.empty());
Simple.notify(this, tmp);
assertTrue (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimpleNoSender);
Simple -= delegate(this, &BasicEventTest::onSimpleNoSender);
Simple.notify(this, tmp);
assertTrue (_count == 0);
ConstSimple += delegate(this, &BasicEventTest::onConstSimple);
ConstSimple -= delegate(this, &BasicEventTest::onConstSimple);
ConstSimple.notify(this, tmp);
assertTrue (_count == 0);
//Note: passing &args will not work due to &
EventArgs* pArgs = &args;
Complex += delegate(this, &BasicEventTest::onComplex);
Complex -= delegate(this, &BasicEventTest::onComplex);
Complex.notify(this, pArgs);
assertTrue (_count == 0);
Complex2 += delegate(this, &BasicEventTest::onComplex2);
Complex2 -= delegate(this, &BasicEventTest::onComplex2);
Complex2.notify(this, args);
assertTrue (_count == 0);
const EventArgs* pCArgs = &args;
ConstComplex += delegate(this, &BasicEventTest::onConstComplex);
ConstComplex -= delegate(this, &BasicEventTest::onConstComplex);
ConstComplex.notify(this, pCArgs);
assertTrue (_count == 0);
Const2Complex += delegate(this, &BasicEventTest::onConst2Complex);
Const2Complex -= delegate(this, &BasicEventTest::onConst2Complex);
Const2Complex.notify(this, pArgs);
assertTrue (_count == 0);
Simple += delegate(&BasicEventTest::onStaticSimple);
Simple += delegate(&BasicEventTest::onStaticSimple);
Simple += delegate(&BasicEventTest::onStaticSimple2);
Simple += delegate(&BasicEventTest::onStaticSimple3);
Simple.notify(this, tmp);
assertTrue (_count == 3);
Simple -= delegate(BasicEventTest::onStaticSimple);
Void += delegate(&BasicEventTest::onStaticVoid);
Void += delegate(&BasicEventTest::onStaticVoid);
Void.notify(this);
assertTrue (_count == 5);
Void -= delegate(BasicEventTest::onStaticVoid);
}
void BasicEventTest::testSingleDelegate()
{
int tmp = 0;
EventArgs args;
assertTrue (_count == 0);
Void += delegate(this, &BasicEventTest::onVoid);
Void.notify(this);
assertTrue (_count == 1);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 2);
ConstSimple += delegate(this, &BasicEventTest::onConstSimple);
ConstSimple.notify(this, tmp);
assertTrue (_count == 3);
EventArgs* pArgs = &args;
Complex += delegate(this, &BasicEventTest::onComplex);
Complex.notify(this, pArgs);
assertTrue (_count == 4);
Complex2 += delegate(this, &BasicEventTest::onComplex2);
Complex2.notify(this, args);
assertTrue (_count == 5);
const EventArgs* pCArgs = &args;
ConstComplex += delegate(this, &BasicEventTest::onConstComplex);
ConstComplex.notify(this, pCArgs);
assertTrue (_count == 6);
Const2Complex += delegate(this, &BasicEventTest::onConst2Complex);
Const2Complex.notify(this, pArgs);
assertTrue (_count == 7);
// check if 2nd notify also works
Const2Complex.notify(this, pArgs);
assertTrue (_count == 8);
}
void BasicEventTest::testDuplicateRegister()
{
int tmp = 0;
assertTrue (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 2);
Simple -= delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 3);
}
void BasicEventTest::testNullMutex()
{
Poco::BasicEvent<int, NullMutex> ev;
int tmp = 0;
assertTrue (_count == 0);
ev += delegate(this, &BasicEventTest::onSimple);
ev += delegate(this, &BasicEventTest::onSimple);
ev.notify(this, tmp);
assertTrue (_count == 2);
ev -= delegate(this, &BasicEventTest::onSimple);
ev.notify(this, tmp);
assertTrue (_count == 3);
}
void BasicEventTest::testDuplicateUnregister()
{
// duplicate unregister shouldn't give an error,
int tmp = 0;
assertTrue (_count == 0);
Simple -= delegate(this, &BasicEventTest::onSimple); // should work
Simple.notify(this, tmp);
assertTrue (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 1);
Simple -= delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 1);
Simple -= delegate(this, &BasicEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 1);
}
void BasicEventTest::testDisabling()
{
int tmp = 0;
assertTrue (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple);
Simple.disable();
Simple.notify(this, tmp);
assertTrue (_count == 0);
Simple.enable();
Simple.notify(this, tmp);
assertTrue (_count == 1);
// unregister should also work with disabled event
Simple.disable();
Simple -= delegate(this, &BasicEventTest::onSimple);
Simple.enable();
Simple.notify(this, tmp);
assertTrue (_count == 1);
}
void BasicEventTest::testExpire()
{
int tmp = 0;
assertTrue (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple, 500);
Simple.notify(this, tmp);
assertTrue (_count == 1);
Poco::Thread::sleep(700);
Simple.notify(this, tmp);
assertTrue (_count == 1);
Simple += delegate(&BasicEventTest::onStaticSimple, 400);
Simple += delegate(&BasicEventTest::onStaticSimple, 400);
Simple += delegate(&BasicEventTest::onStaticSimple2, 400);
Simple += delegate(&BasicEventTest::onStaticSimple3, 400);
Simple.notify(this, tmp);
assertTrue (_count == 4);
Poco::Thread::sleep(700);
Simple.notify(this, tmp);
assertTrue (_count == 4);
}
void BasicEventTest::testExpireReRegister()
{
int tmp = 0;
assertTrue (_count == 0);
Simple += delegate(this, &BasicEventTest::onSimple, 500);
Simple.notify(this, tmp);
assertTrue (_count == 1);
Poco::Thread::sleep(200);
Simple.notify(this, tmp);
assertTrue (_count == 2);
// renew registration
Simple += delegate(this, &BasicEventTest::onSimple, 600);
Poco::Thread::sleep(400);
Simple.notify(this, tmp);
assertTrue (_count == 3);
Poco::Thread::sleep(300);
Simple.notify(this, tmp);
assertTrue (_count == 3);
}
void BasicEventTest::testReturnParams()
{
DummyDelegate o1;
Simple += delegate(&o1, &DummyDelegate::onSimple);
int tmp = 0;
Simple.notify(this, tmp);
assertTrue (tmp == 1);
}
void BasicEventTest::testOverwriteDelegate()
{
DummyDelegate o1;
Simple += delegate(&o1, &DummyDelegate::onSimple);
Simple += delegate(&o1, &DummyDelegate::onSimple2);
int tmp = 0; // onsimple requires 0 as input
Simple.notify(this, tmp);
assertTrue (tmp == 2);
}
void BasicEventTest::testAsyncNotify()
{
Poco::BasicEvent<int>* pSimple= new Poco::BasicEvent<int>();
(*pSimple) += delegate(this, &BasicEventTest::onAsync);
assertTrue (_count == 0);
int tmp = 0;
Poco::ActiveResult<int>retArg = pSimple->notifyAsync(this, tmp);
delete pSimple; // must work even when the event got deleted!
pSimple = NULL;
assertTrue (_count == 0);
retArg.wait();
assertTrue (retArg.data() == tmp);
assertTrue (_count == LARGEINC);
}
void BasicEventTest::onStaticVoid(const void* pSender)
{
BasicEventTest* p = const_cast<BasicEventTest*>(reinterpret_cast<const BasicEventTest*>(pSender));
p->_count++;
}
void BasicEventTest::onVoid(const void* pSender)
{
_count++;
}
void BasicEventTest::onSimpleNoSender(int& i)
{
_count++;
}
void BasicEventTest::onSimple(const void* pSender, int& i)
{
_count++;
}
void BasicEventTest::onStaticSimple(const void* pSender, int& i)
{
BasicEventTest* p = const_cast<BasicEventTest*>(reinterpret_cast<const BasicEventTest*>(pSender));
p->_count++;
}
void BasicEventTest::onStaticSimple2(void* pSender, int& i)
{
BasicEventTest* p = reinterpret_cast<BasicEventTest*>(pSender);
p->_count++;
}
void BasicEventTest::onStaticSimple3(int& i)
{
}
void BasicEventTest::onSimpleOther(const void* pSender, int& i)
{
_count+=100;
}
void BasicEventTest::onConstSimple(const void* pSender, const int& i)
{
_count++;
}
void BasicEventTest::onComplex(const void* pSender, Poco::EventArgs* & i)
{
_count++;
}
void BasicEventTest::onComplex2(const void* pSender, Poco::EventArgs & i)
{
_count++;
}
void BasicEventTest::onConstComplex(const void* pSender, const Poco::EventArgs*& i)
{
_count++;
}
void BasicEventTest::onConst2Complex(const void* pSender, const Poco::EventArgs * const & i)
{
_count++;
}
void BasicEventTest::onAsync(const void* pSender, int& i)
{
Poco::Thread::sleep(700);
_count += LARGEINC ;
}
int BasicEventTest::getCount() const
{
return _count;
}
void BasicEventTest::setUp()
{
_count = 0;
// must clear events, otherwise repeating test executions will fail
// because tests are only created once, only setup is called before
// each test run
Void.clear();
Simple.clear();
ConstSimple.clear();
Complex.clear();
Complex2.clear();
ConstComplex.clear();
Const2Complex.clear();
}
void BasicEventTest::tearDown()
{
}
CppUnit::Test* BasicEventTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("BasicEventTest");
CppUnit_addTest(pSuite, BasicEventTest, testNoDelegate);
CppUnit_addTest(pSuite, BasicEventTest, testSingleDelegate);
CppUnit_addTest(pSuite, BasicEventTest, testReturnParams);
CppUnit_addTest(pSuite, BasicEventTest, testDuplicateRegister);
CppUnit_addTest(pSuite, BasicEventTest, testDuplicateUnregister);
CppUnit_addTest(pSuite, BasicEventTest, testDisabling);
CppUnit_addTest(pSuite, BasicEventTest, testExpire);
CppUnit_addTest(pSuite, BasicEventTest, testExpireReRegister);
CppUnit_addTest(pSuite, BasicEventTest, testOverwriteDelegate);
CppUnit_addTest(pSuite, BasicEventTest, testAsyncNotify);
CppUnit_addTest(pSuite, BasicEventTest, testNullMutex);
return pSuite;
}

View File

@@ -0,0 +1,78 @@
//
// BasicEventTest.h
//
// Tests for BasicEvent
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef BasicEventTest_INCLUDED
#define BasicEventTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
#include "Poco/BasicEvent.h"
#include "Poco/EventArgs.h"
class BasicEventTest: public CppUnit::TestCase
{
Poco::BasicEvent<void> Void;
Poco::BasicEvent<int> Simple;
Poco::BasicEvent<const int> ConstSimple;
Poco::BasicEvent<Poco::EventArgs*> Complex;
Poco::BasicEvent<Poco::EventArgs> Complex2;
Poco::BasicEvent<const Poco::EventArgs*> ConstComplex;
Poco::BasicEvent<const Poco::EventArgs * const> Const2Complex;
public:
BasicEventTest(const std::string& name);
~BasicEventTest();
void testNoDelegate();
void testSingleDelegate();
void testDuplicateRegister();
void testDuplicateUnregister();
void testDisabling();
void testExpire();
void testExpireReRegister();
void testReturnParams();
void testOverwriteDelegate();
void testAsyncNotify();
void testNullMutex();
void setUp();
void tearDown();
static CppUnit::Test* suite();
protected:
static void onStaticVoid(const void* pSender);
void onVoid(const void* pSender);
static void onStaticSimple(const void* pSender, int& i);
static void onStaticSimple2(void* pSender, int& i);
static void onStaticSimple3(int& i);
void onSimpleNoSender(int& i);
void onSimple(const void* pSender, int& i);
void onSimpleOther(const void* pSender, int& i);
void onConstSimple(const void* pSender, const int& i);
void onComplex(const void* pSender, Poco::EventArgs* & i);
void onComplex2(const void* pSender, Poco::EventArgs & i);
void onConstComplex(const void* pSender, const Poco::EventArgs*& i);
void onConst2Complex(const void* pSender, const Poco::EventArgs * const & i);
void onAsync(const void* pSender, int& i);
int getCount() const;
private:
int _count;
};
#endif // BasicEventTest_INCLUDED

View File

@@ -0,0 +1,281 @@
//
// BinaryReaderWriterTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "BinaryReaderWriterTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/BinaryWriter.h"
#include "Poco/BinaryReader.h"
#include "Poco/Buffer.h"
#include <sstream>
using Poco::BinaryWriter;
using Poco::MemoryBinaryWriter;
using Poco::BinaryReader;
using Poco::MemoryBinaryReader;
using Poco::Buffer;
using Poco::Int32;
using Poco::UInt32;
using Poco::Int64;
using Poco::UInt64;
BinaryReaderWriterTest::BinaryReaderWriterTest(const std::string& name): CppUnit::TestCase(name)
{
}
BinaryReaderWriterTest::~BinaryReaderWriterTest()
{
}
void BinaryReaderWriterTest::testNative()
{
std::stringstream sstream;
BinaryWriter writer(sstream);
BinaryReader reader(sstream);
write(writer);
read(reader);
}
void BinaryReaderWriterTest::testBigEndian()
{
std::stringstream sstream;
BinaryWriter writer(sstream, BinaryWriter::BIG_ENDIAN_BYTE_ORDER);
BinaryReader reader(sstream, BinaryReader::UNSPECIFIED_BYTE_ORDER);
assertTrue (writer.byteOrder() == BinaryWriter::BIG_ENDIAN_BYTE_ORDER);
writer.writeBOM();
write(writer);
reader.readBOM();
assertTrue (reader.byteOrder() == BinaryReader::BIG_ENDIAN_BYTE_ORDER);
read(reader);
}
void BinaryReaderWriterTest::testLittleEndian()
{
std::stringstream sstream;
BinaryWriter writer(sstream, BinaryWriter::LITTLE_ENDIAN_BYTE_ORDER);
BinaryReader reader(sstream, BinaryReader::UNSPECIFIED_BYTE_ORDER);
assertTrue (writer.byteOrder() == BinaryWriter::LITTLE_ENDIAN_BYTE_ORDER);
writer.writeBOM();
write(writer);
reader.readBOM();
assertTrue (reader.byteOrder() == BinaryReader::LITTLE_ENDIAN_BYTE_ORDER);
read(reader);
}
void BinaryReaderWriterTest::write(BinaryWriter& writer)
{
writer << true;
writer << false;
writer << 'a';
writer << (short) -100;
writer << (unsigned short) 50000;
writer << -123456;
writer << (unsigned) 123456;
writer << (long) -1234567890;
writer << (unsigned long) 1234567890;
#if defined(POCO_HAVE_INT64)
writer << (Int64) -1234567890;
writer << (UInt64) 1234567890;
#endif
writer << (float) 1.5;
writer << (double) -1.5;
writer << "foo";
writer << "";
writer << std::string("bar");
writer << std::string();
writer.write7BitEncoded((UInt32) 100);
writer.write7BitEncoded((UInt32) 1000);
writer.write7BitEncoded((UInt32) 10000);
writer.write7BitEncoded((UInt32) 100000);
writer.write7BitEncoded((UInt32) 1000000);
#if defined(POCO_HAVE_INT64)
writer.write7BitEncoded((UInt64) 100);
writer.write7BitEncoded((UInt64) 1000);
writer.write7BitEncoded((UInt64) 10000);
writer.write7BitEncoded((UInt64) 100000);
writer.write7BitEncoded((UInt64) 1000000);
#endif
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
writer << vec;
writer.writeRaw("RAW");
}
void BinaryReaderWriterTest::read(BinaryReader& reader)
{
bool b;
reader >> b;
assertTrue (b);
reader >> b;
assertTrue (!b);
char c;
reader >> c;
assertTrue (c == 'a');
short shortv;
reader >> shortv;
assertTrue (shortv == -100);
unsigned short ushortv;
reader >> ushortv;
assertTrue (ushortv == 50000);
int intv;
reader >> intv;
assertTrue (intv == -123456);
unsigned uintv;
reader >> uintv;
assertTrue (uintv == 123456);
long longv;
reader >> longv;
assertTrue (longv == -1234567890);
unsigned long ulongv;
reader >> ulongv;
assertTrue (ulongv == 1234567890);
#if defined(POCO_HAVE_INT64)
Int64 int64v;
reader >> int64v;
assertTrue (int64v == -1234567890);
UInt64 uint64v;
reader >> uint64v;
assertTrue (uint64v == 1234567890);
#endif
float floatv;
reader >> floatv;
assertTrue (floatv == 1.5);
double doublev;
reader >> doublev;
assertTrue (doublev == -1.5);
std::string str;
reader >> str;
assertTrue (str == "foo");
reader >> str;
assertTrue (str == "");
reader >> str;
assertTrue (str == "bar");
reader >> str;
assertTrue (str == "");
UInt32 uint32v;
reader.read7BitEncoded(uint32v);
assertTrue (uint32v == 100);
reader.read7BitEncoded(uint32v);
assertTrue (uint32v == 1000);
reader.read7BitEncoded(uint32v);
assertTrue (uint32v == 10000);
reader.read7BitEncoded(uint32v);
assertTrue (uint32v == 100000);
reader.read7BitEncoded(uint32v);
assertTrue (uint32v == 1000000);
#if defined(POCO_HAVE_INT64)
reader.read7BitEncoded(uint64v);
assertTrue (uint64v == 100);
reader.read7BitEncoded(uint64v);
assertTrue (uint64v == 1000);
reader.read7BitEncoded(uint64v);
assertTrue (uint64v == 10000);
reader.read7BitEncoded(uint64v);
assertTrue (uint64v == 100000);
reader.read7BitEncoded(uint64v);
assertTrue (uint64v == 1000000);
#endif
std::vector<int> vec;
reader >> vec;
assertTrue (vec.size() == 3);
assertTrue (vec[0] == 1);
assertTrue (vec[1] == 2);
assertTrue (vec[2] == 3);
reader.readRaw(3, str);
assertTrue (str == "RAW");
}
void BinaryReaderWriterTest::testWrappers()
{
bool b = false; char c = '0'; int i = 0;
Buffer<char> buf(2 * sizeof(bool) + sizeof(char) + 2 * sizeof(int));
MemoryBinaryWriter writer(buf);
writer << true;
writer << false;
writer << 'a';
writer << 1;
writer << -1;
MemoryBinaryReader reader(writer.data());
reader >> b; assertTrue (b);
reader >> b; assertTrue (!b);
reader >> c; assertTrue ('a' == c);
assertTrue (reader.available() == sizeof(i) * 2);
reader >> i; assertTrue (1 == i);
assertTrue (reader.available() == sizeof(i));
reader >> i; assertTrue (-1 == i);
assertTrue (reader.available() == 0);
reader.setExceptions(std::istream::eofbit);
try
{
reader >> i;
fail ("must throw on EOF");
} catch(std::exception&) { }
}
void BinaryReaderWriterTest::setUp()
{
}
void BinaryReaderWriterTest::tearDown()
{
}
CppUnit::Test* BinaryReaderWriterTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("BinaryReaderWriterTest");
CppUnit_addTest(pSuite, BinaryReaderWriterTest, testNative);
CppUnit_addTest(pSuite, BinaryReaderWriterTest, testBigEndian);
CppUnit_addTest(pSuite, BinaryReaderWriterTest, testLittleEndian);
CppUnit_addTest(pSuite, BinaryReaderWriterTest, testWrappers);
return pSuite;
}

View File

@@ -0,0 +1,45 @@
//
// BinaryReaderWriterTest.h
//
// Definition of the BinaryReaderWriterTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef BinaryReaderWriterTest_INCLUDED
#define BinaryReaderWriterTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
#include "Poco/BinaryReader.h"
#include "Poco/BinaryWriter.h"
class BinaryReaderWriterTest: public CppUnit::TestCase
{
public:
BinaryReaderWriterTest(const std::string& name);
~BinaryReaderWriterTest();
void testNative();
void testBigEndian();
void testLittleEndian();
void testWrappers();
void write(Poco::BinaryWriter& writer);
void read(Poco::BinaryReader& reader);
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // BinaryReaderWriterTest_INCLUDED

View File

@@ -0,0 +1,611 @@
//
// ByteOrderTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ByteOrderTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/ByteOrder.h"
using Poco::ByteOrder;
using Poco::Int16;
using Poco::UInt16;
using Poco::Int32;
using Poco::UInt32;
#if defined(POCO_HAVE_INT64)
using Poco::Int64;
using Poco::UInt64;
#endif
ByteOrderTest::ByteOrderTest(const std::string& name): CppUnit::TestCase(name)
{
}
ByteOrderTest::~ByteOrderTest()
{
}
void ByteOrderTest::testByteOrderFlip()
{
{
Int16 norm = (Int16) 0xAABB;
Int16 flip = ByteOrder::flipBytes(norm);
assertTrue (UInt16(flip) == 0xBBAA);
flip = ByteOrder::flipBytes(flip);
assertTrue (flip == norm);
}
{
UInt16 norm = (UInt16) 0xAABB;
UInt16 flip = ByteOrder::flipBytes(norm);
assertTrue (flip == 0xBBAA);
flip = ByteOrder::flipBytes(flip);
assertTrue (flip == norm);
}
{
Int32 norm = 0xAABBCCDD;
Int32 flip = ByteOrder::flipBytes(norm);
assertTrue (UInt32(flip) == 0xDDCCBBAA);
flip = ByteOrder::flipBytes(flip);
assertTrue (flip == norm);
}
{
UInt32 norm = 0xAABBCCDD;
UInt32 flip = ByteOrder::flipBytes(norm);
assertTrue (flip == 0xDDCCBBAA);
flip = ByteOrder::flipBytes(flip);
assertTrue (flip == norm);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = (Int64(0x8899AABB) << 32) + 0xCCDDEEFF;
Int64 flip = ByteOrder::flipBytes(norm);
assertTrue (flip == (Int64(0xFFEEDDCC) << 32) + 0xBBAA9988);
flip = ByteOrder::flipBytes(flip);
assertTrue (flip == norm);
}
{
UInt64 norm = (UInt64(0x8899AABB) << 32) + 0xCCDDEEFF;
UInt64 flip = ByteOrder::flipBytes(norm);
assertTrue (flip == (UInt64(0xFFEEDDCC) << 32) + 0xBBAA9988);
flip = ByteOrder::flipBytes(flip);
assertTrue (flip == norm);
}
#endif
}
void ByteOrderTest::testByteOrderBigEndian()
{
#if defined(POCO_ARCH_BIG_ENDIAN)
//
// big-endian systems
//
{
Int16 norm = 4;
Int16 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm == flip);
}
#endif
{
Int16 norm = 4;
Int16 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm == flip);
}
#endif
#else
//
// little-endian systems
//
{
Int16 norm = 4;
Int16 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::toBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#endif
{
Int16 norm = 4;
Int16 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::fromBigEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#endif
#endif
}
void ByteOrderTest::testByteOrderLittleEndian()
{
#if defined(POCO_ARCH_LITTLE_ENDIAN)
//
// big-endian systems
//
{
Int16 norm = 4;
Int16 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
#endif
{
Int16 norm = 4;
Int16 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm == flip);
}
#endif
#else
//
// little-endian systems
//
{
Int16 norm = 4;
Int16 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::toLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#endif
{
Int16 norm = 4;
Int16 flip = ByteOrder::fromLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::fromLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::fromLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::fromLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::fromLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::fromLittleEndian(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#endif
#endif
}
void ByteOrderTest::testByteOrderNetwork()
{
#if defined(POCO_ARCH_BIG_ENDIAN)
//
// big-endian systems
//
{
Int16 norm = 4;
Int16 flip = ByteOrder::toNetwork(norm);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::toNetwork(norm);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::toNetwork(norm);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::toNetwork(norm);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::toNetwork(norm);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::toNetwork(norm);
assertTrue (norm == flip);
}
#endif
{
Int16 norm = 4;
Int16 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm == flip);
}
#endif
#else
//
// little-endian systems
//
{
Int16 norm = 4;
Int16 flip = ByteOrder::toNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::toNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::toNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::toNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::toNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::toNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#endif
{
Int16 norm = 4;
Int16 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt16 norm = 4;
UInt16 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
Int32 norm = 4;
Int32 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt32 norm = 4;
UInt32 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#if defined(POCO_HAVE_INT64)
{
Int64 norm = 4;
Int64 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
{
UInt64 norm = 4;
UInt64 flip = ByteOrder::fromNetwork(norm);
assertTrue (norm != flip);
flip = ByteOrder::flipBytes(flip);
assertTrue (norm == flip);
}
#endif
#endif
}
void ByteOrderTest::setUp()
{
}
void ByteOrderTest::tearDown()
{
}
CppUnit::Test* ByteOrderTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ByteOrderTest");
CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderFlip);
CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderBigEndian);
CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderLittleEndian);
CppUnit_addTest(pSuite, ByteOrderTest, testByteOrderNetwork);
return pSuite;
}

View File

@@ -0,0 +1,41 @@
//
// ByteOrderTest.h
//
// Definition of the ByteOrderTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ByteOrderTest_INCLUDED
#define ByteOrderTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ByteOrderTest: public CppUnit::TestCase
{
public:
ByteOrderTest(const std::string& name);
~ByteOrderTest();
void testByteOrderFlip();
void testByteOrderBigEndian();
void testByteOrderLittleEndian();
void testByteOrderNetwork();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // ByteOrderTest_INCLUDED

View File

@@ -0,0 +1,29 @@
//
// CacheTestSuite.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "CacheTestSuite.h"
#include "LRUCacheTest.h"
#include "ExpireCacheTest.h"
#include "ExpireLRUCacheTest.h"
#include "UniqueExpireCacheTest.h"
#include "UniqueExpireLRUCacheTest.h"
CppUnit::Test* CacheTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CacheTestSuite");
pSuite->addTest(LRUCacheTest::suite());
pSuite->addTest(ExpireCacheTest::suite());
pSuite->addTest(UniqueExpireCacheTest::suite());
pSuite->addTest(ExpireLRUCacheTest::suite());
pSuite->addTest(UniqueExpireLRUCacheTest::suite());
return pSuite;
}

View File

@@ -0,0 +1,27 @@
//
// CacheTestSuite.h
//
// Definition of the CacheTestSuite class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef CacheTestSuite_INCLUDED
#define CacheTestSuite_INCLUDED
#include "CppUnit/TestSuite.h"
class CacheTestSuite
{
public:
static CppUnit::Test* suite();
};
#endif // CacheTestSuite_INCLUDED

View File

@@ -0,0 +1,138 @@
//
// ChannelTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ChannelTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/SplitterChannel.h"
#include "Poco/AsyncChannel.h"
#include "Poco/AutoPtr.h"
#include "Poco/Message.h"
#include "Poco/Formatter.h"
#include "Poco/FormattingChannel.h"
#include "Poco/ConsoleChannel.h"
#include "Poco/StreamChannel.h"
#include "TestChannel.h"
#include <sstream>
using Poco::SplitterChannel;
using Poco::AsyncChannel;
using Poco::FormattingChannel;
using Poco::ConsoleChannel;
using Poco::StreamChannel;
using Poco::Formatter;
using Poco::Message;
using Poco::AutoPtr;
class SimpleFormatter: public Formatter
{
public:
void format(const Message& msg, std::string& text)
{
text = msg.getSource();
text.append(": ");
text.append(msg.getText());
}
};
ChannelTest::ChannelTest(const std::string& name): CppUnit::TestCase(name)
{
}
ChannelTest::~ChannelTest()
{
}
void ChannelTest::testSplitter()
{
AutoPtr<TestChannel> pChannel = new TestChannel;
AutoPtr<SplitterChannel> pSplitter = new SplitterChannel;
pSplitter->addChannel(pChannel);
pSplitter->addChannel(pChannel);
Message msg;
pSplitter->log(msg);
assertTrue (pChannel->list().size() == 2);
}
void ChannelTest::testAsync()
{
AutoPtr<TestChannel> pChannel = new TestChannel;
AutoPtr<AsyncChannel> pAsync = new AsyncChannel(pChannel);
pAsync->open();
Message msg;
pAsync->log(msg);
pAsync->log(msg);
pAsync->close();
assertTrue (pChannel->list().size() == 2);
}
void ChannelTest::testFormatting()
{
AutoPtr<TestChannel> pChannel = new TestChannel;
AutoPtr<Formatter> pFormatter = new SimpleFormatter;
AutoPtr<FormattingChannel> pFormatterChannel = new FormattingChannel(pFormatter, pChannel);
Message msg("Source", "Text", Message::PRIO_INFORMATION);
pFormatterChannel->log(msg);
assertTrue (pChannel->list().size() == 1);
assertTrue (pChannel->list().begin()->getText() == "Source: Text");
}
void ChannelTest::testConsole()
{
AutoPtr<ConsoleChannel> pChannel = new ConsoleChannel;
AutoPtr<Formatter> pFormatter = new SimpleFormatter;
AutoPtr<FormattingChannel> pFormatterChannel = new FormattingChannel(pFormatter, pChannel);
Message msg("Source", "Text", Message::PRIO_INFORMATION);
pFormatterChannel->log(msg);
}
void ChannelTest::testStream()
{
std::ostringstream str;
AutoPtr<StreamChannel> pChannel = new StreamChannel(str);
AutoPtr<Formatter> pFormatter = new SimpleFormatter;
AutoPtr<FormattingChannel> pFormatterChannel = new FormattingChannel(pFormatter, pChannel);
Message msg("Source", "Text", Message::PRIO_INFORMATION);
pFormatterChannel->log(msg);
assertTrue (str.str().find("Source: Text") == 0);
}
void ChannelTest::setUp()
{
}
void ChannelTest::tearDown()
{
}
CppUnit::Test* ChannelTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ChannelTest");
CppUnit_addTest(pSuite, ChannelTest, testSplitter);
CppUnit_addTest(pSuite, ChannelTest, testAsync);
CppUnit_addTest(pSuite, ChannelTest, testFormatting);
CppUnit_addTest(pSuite, ChannelTest, testConsole);
CppUnit_addTest(pSuite, ChannelTest, testStream);
return pSuite;
}

View File

@@ -0,0 +1,42 @@
//
// ChannelTest.h
//
// Definition of the ChannelTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ChannelTest_INCLUDED
#define ChannelTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ChannelTest: public CppUnit::TestCase
{
public:
ChannelTest(const std::string& name);
~ChannelTest();
void testSplitter();
void testAsync();
void testFormatting();
void testConsole();
void testStream();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // ChannelTest_INCLUDED

View File

@@ -0,0 +1,212 @@
//
// ClassLoaderTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ClassLoaderTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/ClassLoader.h"
#include "Poco/Manifest.h"
#include "Poco/Exception.h"
#include "TestPlugin.h"
using Poco::ClassLoader;
using Poco::Manifest;
using Poco::SharedLibrary;
using Poco::AbstractMetaObject;
using Poco::NotFoundException;
using Poco::InvalidAccessException;
ClassLoaderTest::ClassLoaderTest(const std::string& name): CppUnit::TestCase(name)
{
}
ClassLoaderTest::~ClassLoaderTest()
{
}
void ClassLoaderTest::testClassLoader1()
{
std::string path = "TestLibrary";
path.append(SharedLibrary::suffix());
ClassLoader<TestPlugin> cl;
assertTrue (cl.begin() == cl.end());
assertNullPtr (cl.findClass("PluginA"));
assertNullPtr (cl.findManifest(path));
assertTrue (!cl.isLibraryLoaded(path));
try
{
const ClassLoader<TestPlugin>::Meta& POCO_UNUSED meta = cl.classFor("PluginA");
fail("not found - must throw exception");
}
catch (NotFoundException&)
{
}
catch (...)
{
failmsg("wrong exception");
}
try
{
const ClassLoader<TestPlugin>::Manif& POCO_UNUSED manif = cl.manifestFor(path);
fail("not found - must throw exception");
}
catch (NotFoundException&)
{
}
catch (...)
{
failmsg("wrong exception");
}
}
void ClassLoaderTest::testClassLoader2()
{
std::string path = "TestLibrary";
path.append(SharedLibrary::suffix());
ClassLoader<TestPlugin> cl;
cl.loadLibrary(path);
assertTrue (cl.begin() != cl.end());
assertNotNullPtr (cl.findClass("PluginA"));
assertNotNullPtr (cl.findClass("PluginB"));
assertNotNullPtr (cl.findClass("PluginC"));
assertNotNullPtr (cl.findManifest(path));
assertTrue (cl.isLibraryLoaded(path));
assertTrue (cl.manifestFor(path).size() == 3);
ClassLoader<TestPlugin>::Iterator it = cl.begin();
assertTrue (it != cl.end());
assertTrue (it->first == path);
assertTrue (it->second->size() == 3);
++it;
assertTrue (it == cl.end());
TestPlugin* pPluginA = cl.classFor("PluginA").create();
assertTrue (pPluginA->name() == "PluginA");
assertTrue (!cl.classFor("PluginA").isAutoDelete(pPluginA));
delete pPluginA;
TestPlugin* pPluginB = cl.classFor("PluginB").create();
assertTrue (pPluginB->name() == "PluginB");
delete pPluginB;
pPluginB = cl.create("PluginB");
assertTrue (pPluginB->name() == "PluginB");
delete pPluginB;
assertTrue (cl.canCreate("PluginA"));
assertTrue (cl.canCreate("PluginB"));
assertTrue (!cl.canCreate("PluginC"));
TestPlugin& pluginC = cl.instance("PluginC");
assertTrue (pluginC.name() == "PluginC");
try
{
TestPlugin& POCO_UNUSED plgB = cl.instance("PluginB");
fail("not a singleton - must throw");
}
catch (InvalidAccessException&)
{
}
try
{
TestPlugin* POCO_UNUSED pPluginC = cl.create("PluginC");
fail("cannot create a singleton - must throw");
}
catch (InvalidAccessException&)
{
}
try
{
const AbstractMetaObject<TestPlugin>& meta = cl.classFor("PluginC");
meta.autoDelete(&(meta.instance()));
fail("cannot take ownership of a singleton - must throw");
}
catch (InvalidAccessException&)
{
}
const AbstractMetaObject<TestPlugin>& meta1 = cl.classFor("PluginC");
assertTrue (meta1.isAutoDelete(&(meta1.instance())));
// the following must not produce memory leaks
const AbstractMetaObject<TestPlugin>& meta2 = cl.classFor("PluginA");
meta2.autoDelete(meta2.create());
meta2.autoDelete(meta2.create());
TestPlugin* pPlugin = meta2.create();
meta2.autoDelete(pPlugin);
assertTrue (meta2.isAutoDelete(pPlugin));
meta2.destroy(pPlugin);
assertTrue (!meta2.isAutoDelete(pPlugin));
cl.unloadLibrary(path);
}
void ClassLoaderTest::testClassLoader3()
{
std::string path = "TestLibrary";
path.append(SharedLibrary::suffix());
ClassLoader<TestPlugin> cl;
cl.loadLibrary(path);
cl.loadLibrary(path);
cl.unloadLibrary(path);
assertTrue (cl.manifestFor(path).size() == 3);
ClassLoader<TestPlugin>::Iterator it = cl.begin();
assertTrue (it != cl.end());
assertTrue (it->first == path);
assertTrue (it->second->size() == 3);
++it;
assertTrue (it == cl.end());
cl.unloadLibrary(path);
assertNullPtr (cl.findManifest(path));
}
void ClassLoaderTest::setUp()
{
}
void ClassLoaderTest::tearDown()
{
}
CppUnit::Test* ClassLoaderTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ClassLoaderTest");
CppUnit_addTest(pSuite, ClassLoaderTest, testClassLoader1);
CppUnit_addTest(pSuite, ClassLoaderTest, testClassLoader2);
CppUnit_addTest(pSuite, ClassLoaderTest, testClassLoader3);
return pSuite;
}

View File

@@ -0,0 +1,40 @@
//
// ClassLoaderTest.h
//
// Definition of the ClassLoaderTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ClassLoaderTest_INCLUDED
#define ClassLoaderTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ClassLoaderTest: public CppUnit::TestCase
{
public:
ClassLoaderTest(const std::string& name);
~ClassLoaderTest();
void testClassLoader1();
void testClassLoader2();
void testClassLoader3();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // ClassLoaderTest_INCLUDED

View File

@@ -0,0 +1,85 @@
//
// ClockTest.cpp
//
// Copyright (c) 2013, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ClockTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Clock.h"
#include "Poco/Thread.h"
#include <iostream>
using Poco::Clock;
using Poco::Thread;
ClockTest::ClockTest(const std::string& name): CppUnit::TestCase(name)
{
}
ClockTest::~ClockTest()
{
}
void ClockTest::testClock()
{
Clock t1;
Thread::sleep(200);
Clock t2;
Clock t3 = t2;
assertTrue (t1 != t2);
assertTrue (!(t1 == t2));
assertTrue (t2 > t1);
assertTrue (t2 >= t1);
assertTrue (!(t1 > t2));
assertTrue (!(t1 >= t2));
assertTrue (t2 == t3);
assertTrue (!(t2 != t3));
assertTrue (t2 >= t3);
assertTrue (t2 <= t3);
Clock::ClockDiff d = (t2 - t1);
assertTrue (d >= 180000 && d <= 300000);
Clock::ClockDiff acc = Clock::accuracy();
assertTrue (acc > 0 && acc < Clock::resolution());
std::cout << "Clock accuracy: " << acc << std::endl;
t1.swap(t2);
assertTrue (t1 > t2);
t2.swap(t1);
Clock now;
Thread::sleep(201);
assertTrue (now.elapsed() >= 200000);
assertTrue (now.isElapsed(200000));
assertTrue (!now.isElapsed(2000000));
}
void ClockTest::setUp()
{
}
void ClockTest::tearDown()
{
}
CppUnit::Test* ClockTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ClockTest");
CppUnit_addTest(pSuite, ClockTest, testClock);
return pSuite;
}

View File

@@ -0,0 +1,38 @@
//
// ClockTest.h
//
// Definition of the ClockTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ClockTest_INCLUDED
#define ClockTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ClockTest: public CppUnit::TestCase
{
public:
ClockTest(const std::string& name);
~ClockTest();
void testClock();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // ClockTest_INCLUDED

View File

@@ -0,0 +1,192 @@
//
// ConditionTest.cpp
//
// Copyright (c) 2007, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ConditionTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Thread.h"
#include "Poco/Runnable.h"
#include "Poco/Condition.h"
#include "Poco/Mutex.h"
#include "Poco/Exception.h"
using Poco::Thread;
using Poco::Runnable;
using Poco::Condition;
using Poco::Mutex;
using Poco::TimeoutException;
namespace
{
class WaitRunnable: public Runnable
{
public:
WaitRunnable(Condition& cond, Mutex& mutex):
_ran(false),
_cond(cond),
_mutex(mutex)
{
}
void run()
{
_mutex.lock();
_cond.wait(_mutex);
_mutex.unlock();
_ran = true;
}
bool ran() const
{
return _ran;
}
private:
bool _ran;
Condition& _cond;
Mutex& _mutex;
};
class TryWaitRunnable: public Runnable
{
public:
TryWaitRunnable(Condition& cond, Mutex& mutex):
_ran(false),
_cond(cond),
_mutex(mutex)
{
}
void run()
{
_mutex.lock();
if (_cond.tryWait(_mutex, 10000))
{
_ran = true;
}
_mutex.unlock();
}
bool ran() const
{
return _ran;
}
private:
bool _ran;
Condition& _cond;
Mutex& _mutex;
};
}
ConditionTest::ConditionTest(const std::string& name): CppUnit::TestCase(name)
{
}
ConditionTest::~ConditionTest()
{
}
void ConditionTest::testSignal()
{
Condition cond;
Mutex mtx;
WaitRunnable r1(cond, mtx);
WaitRunnable r2(cond, mtx);
Thread t1;
Thread t2;
t1.start(r1);
Thread::sleep(200);
t2.start(r2);
assertTrue (!r1.ran());
assertTrue (!r2.ran());
cond.signal();
t1.join();
assertTrue (r1.ran());
assertTrue (!t2.tryJoin(200));
cond.signal();
t2.join();
assertTrue (r2.ran());
}
void ConditionTest::testBroadcast()
{
Condition cond;
Mutex mtx;
WaitRunnable r1(cond, mtx);
WaitRunnable r2(cond, mtx);
TryWaitRunnable r3(cond, mtx);
Thread t1;
Thread t2;
Thread t3;
t1.start(r1);
Thread::sleep(200);
t2.start(r2);
Thread::sleep(200);
t3.start(r3);
assertTrue (!r1.ran());
assertTrue (!r2.ran());
assertTrue (!r3.ran());
cond.signal();
t1.join();
assertTrue (r1.ran());
assertTrue (!t2.tryJoin(500));
assertTrue (!t3.tryJoin(500));
cond.broadcast();
t2.join();
t3.join();
assertTrue (r2.ran());
assertTrue (r3.ran());
}
void ConditionTest::setUp()
{
}
void ConditionTest::tearDown()
{
}
CppUnit::Test* ConditionTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ConditionTest");
CppUnit_addTest(pSuite, ConditionTest, testSignal);
CppUnit_addTest(pSuite, ConditionTest, testBroadcast);
return pSuite;
}

View File

@@ -0,0 +1,39 @@
//
// ConditionTest.h
//
// Definition of the ConditionTest class.
//
// Copyright (c) 2007, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ConditionTest_INCLUDED
#define ConditionTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ConditionTest: public CppUnit::TestCase
{
public:
ConditionTest(const std::string& name);
~ConditionTest();
void testSignal();
void testBroadcast();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // ConditionTest_INCLUDED

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,57 @@
//
// CoreTest.h
//
// Definition of the CoreTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef CoreTest_INCLUDED
#define CoreTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class CoreTest: public CppUnit::TestCase
{
public:
CoreTest(const std::string& name);
~CoreTest();
void testPlatform();
void testFixedLength();
void testBugcheck();
void testFPE();
void testEnvironment();
void testBuffer();
void testFIFOBufferChar();
void testFIFOBufferInt();
void testFIFOBufferEOFAndError();
void testAtomicCounter();
void testNullable();
void testAscii();
void setUp();
void tearDown();
static CppUnit::Test* suite();
protected:
void onReadable(bool& b);
void onWritable(bool& b);
private:
int _readableToNot;
int _notToReadable;
int _writableToNot;
int _notToWritable;
};
#endif // CoreTest_INCLUDED

View File

@@ -0,0 +1,76 @@
//
// CoreTestSuite.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "CoreTestSuite.h"
#include "CoreTest.h"
#include "ArrayTest.h"
#include "AutoPtrTest.h"
#include "SharedPtrTest.h"
#include "AutoReleasePoolTest.h"
#include "ByteOrderTest.h"
#include "StringTest.h"
#include "StringTokenizerTest.h"
#ifndef POCO_VXWORKS
#include "FPETest.h"
#endif
#include "RegularExpressionTest.h"
#include "NDCTest.h"
#include "NumberFormatterTest.h"
#include "NumberParserTest.h"
#include "DynamicFactoryTest.h"
#include "MemoryPoolTest.h"
#include "AnyTest.h"
#include "VarTest.h"
#include "FormatTest.h"
#include "TuplesTest.h"
#ifndef POCO_VXWORKS
#include "NamedTuplesTest.h"
#endif
#include "TypeListTest.h"
#include "ObjectPoolTest.h"
#include "ListMapTest.h"
#include "OrderedContainersTest.h"
CppUnit::Test* CoreTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CoreTestSuite");
pSuite->addTest(CoreTest::suite());
pSuite->addTest(ArrayTest::suite());
pSuite->addTest(AutoPtrTest::suite());
pSuite->addTest(SharedPtrTest::suite());
pSuite->addTest(AutoReleasePoolTest::suite());
pSuite->addTest(ByteOrderTest::suite());
pSuite->addTest(StringTest::suite());
pSuite->addTest(StringTokenizerTest::suite());
#ifndef POCO_VXWORKS
pSuite->addTest(FPETest::suite());
#endif
pSuite->addTest(RegularExpressionTest::suite());
pSuite->addTest(NDCTest::suite());
pSuite->addTest(NumberFormatterTest::suite());
pSuite->addTest(NumberParserTest::suite());
pSuite->addTest(DynamicFactoryTest::suite());
pSuite->addTest(MemoryPoolTest::suite());
pSuite->addTest(AnyTest::suite());
pSuite->addTest(VarTest::suite());
pSuite->addTest(FormatTest::suite());
pSuite->addTest(TuplesTest::suite());
#ifndef POCO_VXWORKS
pSuite->addTest(NamedTuplesTest::suite());
#endif
pSuite->addTest(TypeListTest::suite());
pSuite->addTest(ObjectPoolTest::suite());
pSuite->addTest(ListMapTest::suite());
pSuite->addTest(OrderedContainersTest::suite());
return pSuite;
}

View File

@@ -0,0 +1,27 @@
//
// CoreTestSuite.h
//
// Definition of the CoreTestSuite class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef CoreTestSuite_INCLUDED
#define CoreTestSuite_INCLUDED
#include "CppUnit/TestSuite.h"
class CoreTestSuite
{
public:
static CppUnit::Test* suite();
};
#endif // CoreTestSuite_INCLUDED

View File

@@ -0,0 +1,122 @@
//
// CountingStreamTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "CountingStreamTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/CountingStream.h"
#include <sstream>
using Poco::CountingInputStream;
using Poco::CountingOutputStream;
CountingStreamTest::CountingStreamTest(const std::string& name): CppUnit::TestCase(name)
{
}
CountingStreamTest::~CountingStreamTest()
{
}
void CountingStreamTest::testInput()
{
char c;
std::istringstream istr1("foo");
CountingInputStream ci1(istr1);
while (ci1.good()) ci1.get(c);
assertTrue (ci1.lines() == 1);
assertTrue (ci1.chars() == 3);
assertTrue (ci1.pos() == 3);
std::istringstream istr2("foo\nbar");
CountingInputStream ci2(istr2);
while (ci2.good()) ci2.get(c);
assertTrue (ci2.lines() == 2);
assertTrue (ci2.chars() == 7);
assertTrue (ci2.pos() == 3);
std::istringstream istr3("foo\nbar\n");
CountingInputStream ci3(istr3);
while (ci3.good()) ci3.get(c);
assertTrue (ci3.lines() == 2);
assertTrue (ci3.chars() == 8);
assertTrue (ci3.pos() == 0);
std::istringstream istr4("foo");
CountingInputStream ci4(istr4);
while (ci4.good()) ci4.get(c);
ci4.addChars(10);
ci4.addLines(2);
ci4.addPos(3);
assertTrue (ci4.lines() == 1 + 2);
assertTrue (ci4.chars() == 3 + 10);
assertTrue (ci4.pos() == 3 + 3);
}
void CountingStreamTest::testOutput()
{
std::ostringstream ostr1;
CountingOutputStream co1(ostr1);
co1 << "foo";
assertTrue (ostr1.str() == "foo");
assertTrue (co1.lines() == 1);
assertTrue (co1.chars() == 3);
assertTrue (co1.pos() == 3);
std::ostringstream ostr2;
CountingOutputStream co2(ostr2);
co2 << "foo\nbar";
assertTrue (ostr2.str() == "foo\nbar");
assertTrue (co2.lines() == 2);
assertTrue (co2.chars() == 7);
assertTrue (co2.pos() == 3);
CountingOutputStream co3;
co3 << "foo\nbar\n";
assertTrue (co3.lines() == 2);
assertTrue (co3.chars() == 8);
assertTrue (co3.pos() == 0);
std::ostringstream ostr4;
CountingOutputStream co4(ostr4);
co4 << "foo";
co4.addChars(10);
co4.addLines(2);
co4.addPos(3);
assertTrue (co4.lines() == 1 + 2);
assertTrue (co4.chars() == 3 + 10);
assertTrue (co4.pos() == 3 + 3);
}
void CountingStreamTest::setUp()
{
}
void CountingStreamTest::tearDown()
{
}
CppUnit::Test* CountingStreamTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CountingStreamTest");
CppUnit_addTest(pSuite, CountingStreamTest, testInput);
CppUnit_addTest(pSuite, CountingStreamTest, testOutput);
return pSuite;
}

View File

@@ -0,0 +1,39 @@
//
// CountingStreamTest.h
//
// Definition of the CountingStreamTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef CountingStreamTest_INCLUDED
#define CountingStreamTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class CountingStreamTest: public CppUnit::TestCase
{
public:
CountingStreamTest(const std::string& name);
~CountingStreamTest();
void testInput();
void testOutput();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // CountingStreamTest_INCLUDED

View File

@@ -0,0 +1,38 @@
//
// CryptTestSuite.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "CryptTestSuite.h"
#include "MD4EngineTest.h"
#include "MD5EngineTest.h"
#include "SHA1EngineTest.h"
#include "SHA2EngineTest.h"
#include "HMACEngineTest.h"
#include "PBKDF2EngineTest.h"
#include "DigestStreamTest.h"
#include "RandomTest.h"
#include "RandomStreamTest.h"
CppUnit::Test* CryptTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CryptTestSuite");
pSuite->addTest(MD4EngineTest::suite());
pSuite->addTest(MD5EngineTest::suite());
pSuite->addTest(SHA1EngineTest::suite());
pSuite->addTest(SHA2EngineTest::suite());
pSuite->addTest(HMACEngineTest::suite());
pSuite->addTest(PBKDF2EngineTest::suite());
pSuite->addTest(DigestStreamTest::suite());
pSuite->addTest(RandomTest::suite());
pSuite->addTest(RandomStreamTest::suite());
return pSuite;
}

View File

@@ -0,0 +1,27 @@
//
// CryptTestSuite.h
//
// Definition of the CryptTestSuite class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef CryptTestSuite_INCLUDED
#define CryptTestSuite_INCLUDED
#include "CppUnit/TestSuite.h"
class CryptTestSuite
{
public:
static CppUnit::Test* suite();
};
#endif // CryptTestSuite_INCLUDED

View File

@@ -0,0 +1,113 @@
//
// DataURIStreamTest.cpp
//
// Copyright (c) 2019, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DataURIStreamTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/DataURIStream.h"
#include "Poco/Exception.h"
#include "Poco/URI.h"
#include "Poco/StreamCopier.h"
#include <sstream>
using Poco::DataFormatException;
using Poco::DataURIStream;
using Poco::StreamCopier;
using Poco::URI;
DataURIStreamTest::DataURIStreamTest(const std::string& name): CppUnit::TestCase(name)
{
}
DataURIStreamTest::~DataURIStreamTest()
{
}
void DataURIStreamTest::testWithBase64()
{
{
DataURIStream ds(URI("data:;base64,SGVsbG8sIFdvcmxkIQ%3D%3D"));
std::ostringstream ostr;
StreamCopier::copyStream(ds, ostr);
assertTrue (ostr.str() == "Hello, World!");
}
{
DataURIStream ds(URI("data:text/vnd-example+xyz;foo=bar;base64,R0lGODdh"));
std::ostringstream ostr;
StreamCopier::copyStream(ds, ostr);
assertTrue (ostr.str() == "GIF87a");
}
{
DataURIStream ds(URI("data:application/octet-stream;base64,A+b/7A=="));
std::ostringstream ostr;
StreamCopier::copyStream(ds, ostr);
assertTrue (ostr.str() == "\x03\xE6\xFF\xEC");
}
}
void DataURIStreamTest::testWithoutBase64()
{
{
DataURIStream ds(URI("data:,Hello%2C%20World!"));
std::ostringstream ostr;
StreamCopier::copyStream(ds, ostr);
assertTrue (ostr.str() == "Hello, World!");
}
{
DataURIStream ds(URI("data:text/plain;charset=UTF-8;page=21,the%20data:1234,5678"));
std::ostringstream ostr;
StreamCopier::copyStream(ds, ostr);
assertTrue (ostr.str() == "the data:1234,5678");
}
}
void DataURIStreamTest::testZeroLengthData()
{
{
DataURIStream ds(URI("data:text/plain;base64,"));
std::ostringstream ostr;
StreamCopier::copyStream(ds, ostr);
assertTrue (ostr.str().empty());
}
{
DataURIStream ds(URI("data:,"));
std::ostringstream ostr;
StreamCopier::copyStream(ds, ostr);
assertTrue (ostr.str().empty());
}
}
void DataURIStreamTest::setUp()
{
}
void DataURIStreamTest::tearDown()
{
}
CppUnit::Test* DataURIStreamTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DataURIStreamTest");
CppUnit_addTest(pSuite, DataURIStreamTest, testWithBase64);
CppUnit_addTest(pSuite, DataURIStreamTest, testWithoutBase64);
CppUnit_addTest(pSuite, DataURIStreamTest, testZeroLengthData);
return pSuite;
}

View File

@@ -0,0 +1,37 @@
//
// DataURIStreamTest.h
//
// Definition of the DataURItreamTest class.
//
// Copyright (c) 2019, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DataURIStreamTest_INCLUDED
#define DataURIStreamTest_INCLUDED
#include "CppUnit/TestCase.h"
class DataURIStreamTest: public CppUnit::TestCase
{
public:
DataURIStreamTest(const std::string& name);
~DataURIStreamTest();
void testWithBase64();
void testWithoutBase64();
void testZeroLengthData();
void setUp();
void tearDown();
static CppUnit::Test* suite();
};
#endif // DataURIStreamTest_INCLUDED

View File

@@ -0,0 +1,228 @@
//
// DateTimeFormatterTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DateTimeFormatterTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/DateTime.h"
#include "Poco/Timespan.h"
using Poco::DateTime;
using Poco::Timespan;
using Poco::DateTimeFormat;
using Poco::DateTimeFormatter;
DateTimeFormatterTest::DateTimeFormatterTest(const std::string& name)
: CppUnit::TestCase(name)
{
// Linker regresion SF #3288584
std::string message;
Poco::LocalDateTime now;
Poco::DateTimeFormatter::append(message, now, "%H:%M:%S.%i");
}
DateTimeFormatterTest::~DateTimeFormatterTest()
{
}
void DateTimeFormatterTest::testISO8601()
{
DateTime dt(2005, 1, 8, 12, 30, 00);
std::string str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT);
assertTrue (str == "2005-01-08T12:30:00Z");
str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT, 3600);
assertTrue (str == "2005-01-08T12:30:00+01:00");
str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FORMAT, -3600);
assertTrue (str == "2005-01-08T12:30:00-01:00");
}
void DateTimeFormatterTest::testISO8601Frac()
{
DateTime dt(2005, 1, 8, 12, 30, 00, 12, 34);
std::string str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FRAC_FORMAT);
assertTrue (str == "2005-01-08T12:30:00.012034Z");
str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FRAC_FORMAT, 3600);
assertTrue (str == "2005-01-08T12:30:00.012034+01:00");
str = DateTimeFormatter::format(dt, DateTimeFormat::ISO8601_FRAC_FORMAT, -3600);
assertTrue (str == "2005-01-08T12:30:00.012034-01:00");
}
void DateTimeFormatterTest::testRFC822()
{
DateTime dt(2005, 1, 8, 12, 30, 00);
std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT);
assertTrue (str == "Sat, 8 Jan 05 12:30:00 GMT");
str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT, 3600);
assertTrue (str == "Sat, 8 Jan 05 12:30:00 +0100");
str = DateTimeFormatter::format(dt, DateTimeFormat::RFC822_FORMAT, -3600);
assertTrue (str == "Sat, 8 Jan 05 12:30:00 -0100");
}
void DateTimeFormatterTest::testRFC1123()
{
DateTime dt(2005, 1, 8, 12, 30, 00);
std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT);
assertTrue (str == "Sat, 8 Jan 2005 12:30:00 GMT");
str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT, 3600);
assertTrue (str == "Sat, 8 Jan 2005 12:30:00 +0100");
str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1123_FORMAT, -3600);
assertTrue (str == "Sat, 8 Jan 2005 12:30:00 -0100");
}
void DateTimeFormatterTest::testHTTP()
{
DateTime dt(2005, 1, 8, 12, 30, 00);
std::string str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT);
assertTrue (str == "Sat, 08 Jan 2005 12:30:00 GMT");
str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT, 3600);
assertTrue (str == "Sat, 08 Jan 2005 12:30:00 +0100");
str = DateTimeFormatter::format(dt, DateTimeFormat::HTTP_FORMAT, -3600);
assertTrue (str == "Sat, 08 Jan 2005 12:30:00 -0100");
}
void DateTimeFormatterTest::testRFC850()
{
DateTime dt(2005, 1, 8, 12, 30, 00);
std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT);
assertTrue (str == "Saturday, 8-Jan-05 12:30:00 GMT");
str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT, 3600);
assertTrue (str == "Saturday, 8-Jan-05 12:30:00 +0100");
str = DateTimeFormatter::format(dt, DateTimeFormat::RFC850_FORMAT, -3600);
assertTrue (str == "Saturday, 8-Jan-05 12:30:00 -0100");
}
void DateTimeFormatterTest::testRFC1036()
{
DateTime dt(2005, 1, 8, 12, 30, 00);
std::string str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT);
assertTrue (str == "Saturday, 8 Jan 05 12:30:00 GMT");
str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT, 3600);
assertTrue (str == "Saturday, 8 Jan 05 12:30:00 +0100");
str = DateTimeFormatter::format(dt, DateTimeFormat::RFC1036_FORMAT, -3600);
assertTrue (str == "Saturday, 8 Jan 05 12:30:00 -0100");
}
void DateTimeFormatterTest::testASCTIME()
{
DateTime dt(2005, 1, 8, 12, 30, 00);
std::string str = DateTimeFormatter::format(dt, DateTimeFormat::ASCTIME_FORMAT);
assertTrue (str == "Sat Jan 8 12:30:00 2005");
}
void DateTimeFormatterTest::testSORTABLE()
{
DateTime dt(2005, 1, 8, 12, 30, 00);
std::string str = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT);
assertTrue (str == "2005-01-08 12:30:00");
}
void DateTimeFormatterTest::testCustom()
{
DateTime dt(2005, 1, 8, 12, 30, 00, 250);
std::string str = DateTimeFormatter::format(dt, "%w/%W/%b/%B/%d/%e/%f/%m/%n/%o/%y/%Y/%H/%h/%a/%A/%M/%S/%i/%c/%z/%Z/%%");
assertTrue (str == "Sat/Saturday/Jan/January/08/8/ 8/01/1/ 1/05/2005/12/12/pm/PM/30/00/250/2/Z/GMT/%");
}
void DateTimeFormatterTest::testTimespan()
{
Timespan ts(1, 1, 1, 1, 1000);
std::string str = DateTimeFormatter::format(ts);
assertTrue (str == "1d 01:01:01.001");
Timespan ts1(1, 24, 1, 1, 1000);
str = DateTimeFormatter::format(ts1);
assertTrue (str == "2d 00:01:01.001");
Timespan ts2(1, 25, 1, 1, 1000);
str = DateTimeFormatter::format(ts2);
assertTrue (str == "2d 01:01:01.001");
Timespan ts3(5, 4, 3, 2, 1000);
str = DateTimeFormatter::format(ts3, "%i.%S:%M:%H d%d %%");
assertTrue (str == "001.02:03:04 d5 %");
Timespan ts4(0, 24, 60, 60, 1001000);
str = DateTimeFormatter::format(ts4);
assertTrue (str == "1d 01:01:01.001");
Timespan ts5(2, 11, 30, 20, 0);
str = DateTimeFormatter::format(ts5, "%h %m %s");
assertTrue (str == "59 3570 214220");
}
void DateTimeFormatterTest::setUp()
{
}
void DateTimeFormatterTest::tearDown()
{
}
CppUnit::Test* DateTimeFormatterTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeFormatterTest");
CppUnit_addTest(pSuite, DateTimeFormatterTest, testISO8601);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testISO8601Frac);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC822);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC1123);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testHTTP);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC850);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testRFC1036);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testASCTIME);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testSORTABLE);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testCustom);
CppUnit_addTest(pSuite, DateTimeFormatterTest, testTimespan);
return pSuite;
}

View File

@@ -0,0 +1,48 @@
//
// DateTimeFormatterTest.h
//
// Definition of the DateTimeFormatterTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DateTimeFormatterTest_INCLUDED
#define DateTimeFormatterTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class DateTimeFormatterTest: public CppUnit::TestCase
{
public:
DateTimeFormatterTest(const std::string& name);
~DateTimeFormatterTest();
void testISO8601();
void testISO8601Frac();
void testRFC822();
void testRFC1123();
void testHTTP();
void testRFC850();
void testRFC1036();
void testASCTIME();
void testSORTABLE();
void testCustom();
void testTimespan();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // DateTimeFormatterTest_INCLUDED

View File

@@ -0,0 +1,790 @@
//
// DateTimeParserTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DateTimeParserTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/DateTimeParser.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/DateTime.h"
#include "Poco/Timestamp.h"
#include "Poco/Exception.h"
using Poco::DateTime;
using Poco::DateTimeFormat;
using Poco::DateTimeParser;
using Poco::Timestamp;
using Poco::SyntaxException;
DateTimeParserTest::DateTimeParserTest(const std::string& name): CppUnit::TestCase(name)
{
}
DateTimeParserTest::~DateTimeParserTest()
{
}
void DateTimeParserTest::testISO8601()
{
int tzd;
DateTime dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00Z", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00+01:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00-01:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == -3600);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08T12:30:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FORMAT, "2005-01-08", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
}
void DateTimeParserTest::testISO8601Frac()
{
int tzd;
DateTime dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08T12:30:00Z", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.microsecond() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08T12:30:00+01:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.microsecond() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08T12:30:00-01:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.microsecond() == 0);
assertTrue (tzd == -3600);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08T12:30:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.microsecond() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.microsecond() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08T12:30:00.1Z", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 100);
assertTrue (dt.microsecond() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08T12:30:00.123+01:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 123);
assertTrue (dt.microsecond() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08T12:30:00.12345-01:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 123);
assertTrue (dt.microsecond() == 450);
assertTrue (tzd == -3600);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2010-09-23T16:17:01.2817002+02:00", tzd);
assertTrue (dt.year() == 2010);
assertTrue (dt.month() == 9);
assertTrue (dt.day() == 23);
assertTrue (dt.hour() == 16);
assertTrue (dt.minute() == 17);
assertTrue (dt.second() == 1);
assertTrue (dt.millisecond() == 281);
assertTrue (dt.microsecond() == 700);
assertTrue (tzd == 7200);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08T12:30:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.microsecond() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08T12:30:00.123456", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 123);
assertTrue (dt.microsecond() == 456);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::ISO8601_FRAC_FORMAT, "2005-01-08", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.microsecond() == 0);
assertTrue (tzd == 0);
}
void DateTimeParserTest::testRFC822()
{
int tzd;
DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Sat, 8 Jan 05 12:30:00 GMT", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Sat, 8 Jan 05 12:30:00 +0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Sat, 8 Jan 05 12:30:00 -0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == -3600);
dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Tue, 18 Jan 05 12:30:00 CET", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 18);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "Wed, 12 Sep 73 02:01:12 CEST", tzd);
assertTrue (dt.year() == 1973);
assertTrue (dt.month() == 9);
assertTrue (dt.day() == 12);
assertTrue (dt.hour() == 2);
assertTrue (dt.minute() == 1);
assertTrue (dt.second() == 12);
assertTrue (tzd == 7200);
dt = DateTimeParser::parse(DateTimeFormat::RFC822_FORMAT, "12 Sep 73 02:01:12 CEST", tzd);
assertTrue (dt.year() == 1973);
assertTrue (dt.month() == 9);
assertTrue (dt.day() == 12);
assertTrue (dt.hour() == 2);
assertTrue (dt.minute() == 1);
assertTrue (dt.second() == 12);
assertTrue (tzd == 7200);
}
void DateTimeParserTest::testRFC1123()
{
int tzd;
DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sat, 8 Jan 2005 12:30:00 GMT", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sat, 8 Jan 2005 12:30:00 +0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sat, 8 Jan 2005 12:30:00 -0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == -3600);
dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sun, 20 Jul 1969 16:17:30 EDT", tzd);
assertTrue (dt.year() == 1969);
assertTrue (dt.month() == 7);
assertTrue (dt.day() == 20);
assertTrue (dt.hour() == 16);
assertTrue (dt.minute() == 17);
assertTrue (dt.second() == 30);
assertTrue (tzd == -14400);
dt = DateTimeParser::parse(DateTimeFormat::RFC1123_FORMAT, "Sun, 20 Jul 1969 16:17:30 GMT+01:00", tzd);
assertTrue (dt.year() == 1969);
assertTrue (dt.month() == 7);
assertTrue (dt.day() == 20);
assertTrue (dt.hour() == 16);
assertTrue (dt.minute() == 17);
assertTrue (dt.second() == 30);
assertTrue (tzd == 3600);
}
void DateTimeParserTest::testHTTP()
{
int tzd;
DateTime dt = DateTimeParser::parse(DateTimeFormat::HTTP_FORMAT, "Sat, 08 Jan 2005 12:30:00 GMT", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::HTTP_FORMAT, "Sat, 08 Jan 2005 12:30:00 +0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse(DateTimeFormat::HTTP_FORMAT, "Sat, 08 Jan 2005 12:30:00 -0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == -3600);
}
void DateTimeParserTest::testRFC850()
{
int tzd;
DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Saturday, 8-Jan-05 12:30:00 GMT", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Saturday, 8-Jan-05 12:30:00 +0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Saturday, 8-Jan-05 12:30:00 -0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == -3600);
dt = DateTimeParser::parse(DateTimeFormat::RFC850_FORMAT, "Wed, 12-Sep-73 02:01:12 CEST", tzd);
assertTrue (dt.year() == 1973);
assertTrue (dt.month() == 9);
assertTrue (dt.day() == 12);
assertTrue (dt.hour() == 2);
assertTrue (dt.minute() == 1);
assertTrue (dt.second() == 12);
assertTrue (tzd == 7200);
}
void DateTimeParserTest::testRFC1036()
{
int tzd;
DateTime dt = DateTimeParser::parse(DateTimeFormat::RFC1036_FORMAT, "Saturday, 8 Jan 05 12:30:00 GMT", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::RFC1036_FORMAT, "Saturday, 8 Jan 05 12:30:00 +0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse(DateTimeFormat::RFC1036_FORMAT, "Saturday, 8 Jan 05 12:30:00 -0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == -3600);
}
void DateTimeParserTest::testASCTIME()
{
int tzd;
DateTime dt = DateTimeParser::parse(DateTimeFormat::ASCTIME_FORMAT, "Sat Jan 8 12:30:00 2005", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
}
void DateTimeParserTest::testSORTABLE()
{
int tzd;
DateTime dt = DateTimeParser::parse(DateTimeFormat::SORTABLE_FORMAT, "2005-01-08 12:30:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse(DateTimeFormat::SORTABLE_FORMAT, "2005-01-08", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
}
void DateTimeParserTest::testCustom()
{
int tzd;
DateTime dt = DateTimeParser::parse("%d-%b-%Y", "18-Jan-2005", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 18);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse("%m/%d/%y", "01/18/05", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 18);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse("%h:%M %a", "12:30 am", tzd);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
dt = DateTimeParser::parse("%h:%M %a", "12:30 PM", tzd);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (!DateTimeParser::tryParse("%h:%M %a", "", dt, tzd));
assertTrue (!DateTimeParser::tryParse("", "12:30 PM", dt, tzd));
assertTrue (!DateTimeParser::tryParse("", "", dt, tzd));
try
{
DateTimeParser::parse("%h:%M %a", "", tzd);
fail ("must fail");
}
catch (SyntaxException&)
{
}
try
{
DateTimeParser::parse("", "12:30 PM", tzd);
fail ("must fail");
}
catch (SyntaxException&)
{
}
try
{
DateTimeParser::parse("", "", tzd);
fail ("must fail");
}
catch (SyntaxException&)
{
}
}
void DateTimeParserTest::testGuess()
{
int tzd;
DateTime dt = DateTimeParser::parse("2005-01-08T12:30:00Z", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse("20050108T123000Z", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse("2005-01-08T12:30:00+01:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse("2005-01-08T12:30:00.123456Z", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
assertTrue (dt.millisecond() == 123);
assertTrue (dt.microsecond() == 456);
dt = DateTimeParser::parse("2005-01-08T12:30:00,123456Z", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
assertTrue (dt.millisecond() == 123);
assertTrue (dt.microsecond() == 456);
dt = DateTimeParser::parse("20050108T123000,123456Z", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
assertTrue (dt.millisecond() == 123);
assertTrue (dt.microsecond() == 456);
dt = DateTimeParser::parse("20050108T123000.123+0200", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 7200);
assertTrue (dt.millisecond() == 123);
assertTrue (dt.microsecond() == 0);
dt = DateTimeParser::parse("2005-01-08T12:30:00.123456-02:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == -7200);
assertTrue (dt.millisecond() == 123);
assertTrue (dt.microsecond() == 456);
dt = DateTimeParser::parse("Sat, 8 Jan 05 12:30:00 +0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse("Sat, 8 Jan 2005 12:30:00 +0100", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 3600);
dt = DateTimeParser::parse("Sat Jan 8 12:30:00 2005", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse("2005-01-08 12:30:00", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
dt = DateTimeParser::parse("2005-01-08", tzd);
assertTrue (dt.year() == 2005);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 8);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (tzd == 0);
}
void DateTimeParserTest::testParseMonth()
{
std::string str = "January";
std::string::const_iterator it = str.begin();
int month = DateTimeParser::parseMonth(it, str.end());
assertTrue (month == 1);
str = "February";
it = str.begin();
month = DateTimeParser::parseMonth(it, str.end());
assertTrue (month == 2);
str = "December";
it = str.begin();
month = DateTimeParser::parseMonth(it, str.end());
assertTrue (month == 12);
str = "Jan";
it = str.begin();
month = DateTimeParser::parseMonth(it, str.end());
assertTrue (month == 1);
str = "Feb";
it = str.begin();
month = DateTimeParser::parseMonth(it, str.end());
assertTrue (month == 2);
str = "jan";
it = str.begin();
month = DateTimeParser::parseMonth(it, str.end());
assertTrue (month == 1);
str = "feb";
it = str.begin();
month = DateTimeParser::parseMonth(it, str.end());
assertTrue (month == 2);
try
{
str = "ja";
it = str.begin();
month = DateTimeParser::parseMonth(it, str.end());
fail("Not a valid month name - must throw");
}
catch (SyntaxException&)
{
}
}
void DateTimeParserTest::testParseDayOfWeek()
{
std::string str = "Sunday";
std::string::const_iterator it = str.begin();
int dow = DateTimeParser::parseDayOfWeek(it, str.end());
assertTrue (dow == 0);
str = "Monday";
it = str.begin();
dow = DateTimeParser::parseDayOfWeek(it, str.end());
assertTrue (dow == 1);
str = "Saturday";
it = str.begin();
dow = DateTimeParser::parseDayOfWeek(it, str.end());
assertTrue (dow == 6);
str = "Sun";
it = str.begin();
dow = DateTimeParser::parseDayOfWeek(it, str.end());
assertTrue (dow == 0);
str = "Mon";
it = str.begin();
dow = DateTimeParser::parseDayOfWeek(it, str.end());
assertTrue (dow == 1);
str = "sun";
it = str.begin();
dow = DateTimeParser::parseDayOfWeek(it, str.end());
assertTrue (dow == 0);
str = "mon";
it = str.begin();
dow = DateTimeParser::parseDayOfWeek(it, str.end());
assertTrue (dow == 1);
try
{
str = "su";
it = str.begin();
dow = DateTimeParser::parseDayOfWeek(it, str.end());
fail("Not a valid weekday name - must throw");
}
catch (SyntaxException&)
{
}
}
void DateTimeParserTest::setUp()
{
}
void DateTimeParserTest::tearDown()
{
}
CppUnit::Test* DateTimeParserTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeParserTest");
CppUnit_addTest(pSuite, DateTimeParserTest, testISO8601);
CppUnit_addTest(pSuite, DateTimeParserTest, testISO8601Frac);
CppUnit_addTest(pSuite, DateTimeParserTest, testRFC822);
CppUnit_addTest(pSuite, DateTimeParserTest, testRFC1123);
CppUnit_addTest(pSuite, DateTimeParserTest, testHTTP);
CppUnit_addTest(pSuite, DateTimeParserTest, testRFC850);
CppUnit_addTest(pSuite, DateTimeParserTest, testRFC1036);
CppUnit_addTest(pSuite, DateTimeParserTest, testASCTIME);
CppUnit_addTest(pSuite, DateTimeParserTest, testSORTABLE);
CppUnit_addTest(pSuite, DateTimeParserTest, testCustom);
CppUnit_addTest(pSuite, DateTimeParserTest, testGuess);
CppUnit_addTest(pSuite, DateTimeParserTest, testParseMonth);
CppUnit_addTest(pSuite, DateTimeParserTest, testParseDayOfWeek);
return pSuite;
}

View File

@@ -0,0 +1,50 @@
//
// DateTimeParserTest.h
//
// Definition of the DateTimeParserTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DateTimeParserTest_INCLUDED
#define DateTimeParserTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class DateTimeParserTest: public CppUnit::TestCase
{
public:
DateTimeParserTest(const std::string& name);
~DateTimeParserTest();
void testISO8601();
void testISO8601Frac();
void testRFC822();
void testRFC1123();
void testHTTP();
void testRFC850();
void testRFC1036();
void testASCTIME();
void testSORTABLE();
void testCustom();
void testGuess();
void testParseMonth();
void testParseDayOfWeek();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // DateTimeParserTest_INCLUDED

View File

@@ -0,0 +1,909 @@
//
// DateTimeTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DateTimeTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/DateTime.h"
#include "Poco/Timestamp.h"
#include "Poco/Timespan.h"
#include "Poco/Exception.h"
using Poco::Timestamp;
using Poco::DateTime;
using Poco::Timespan;
using Poco::AssertionViolationException;
DateTimeTest::DateTimeTest(const std::string& name): CppUnit::TestCase(name)
{
}
DateTimeTest::~DateTimeTest()
{
}
void DateTimeTest::testTimestamp()
{
Timestamp ts(0); // Unix epoch 1970-01-01 00:00:00 Thursday
DateTime dt(ts);
assertTrue (dt.year() == 1970);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 1);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.dayOfWeek() == 4);
assertTrue (dt.julianDay() == 2440587.5);
assertTrue (dt.timestamp() == 0);
ts = Timestamp::fromEpochTime(1000000000);
dt = ts; // 2001-09-09 01:46:40 Sunday
assertTrue (dt.year() == 2001);
assertTrue (dt.month() == 9);
assertTrue (dt.day() == 9);
assertTrue (dt.hour() == 1);
assertTrue (dt.minute() == 46);
assertTrue (dt.second() == 40);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.dayOfWeek() == 0);
assertTrue (dt.timestamp().epochTime() == 1000000000);
assertEqualDelta (dt.julianDay(), 2452161.574074, 0.000001);
}
void DateTimeTest::testJulian()
{
DateTime dt(2440587.5); // unix epoch as Julian day
assertTrue (dt.year() == 1970);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 1);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.dayOfWeek() == 4);
assertTrue (dt.julianDay() == 2440587.5);
assertTrue (dt.timestamp() == 0);
dt = 2299160.5; // 1582-10-15 00:00:00 (first day of Gregorian reform, UTC base)
assertTrue (dt.year() == 1582);
assertTrue (dt.month() == 10);
assertTrue (dt.day() == 15);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.dayOfWeek() == 5);
assertTrue (dt.julianDay() == 2299160.5);
dt = 0.0; // -4713-11-24 12:00:00 (Gregorian date of Julian day reference)
assertTrue (dt.year() == -4713);
assertTrue (dt.month() == 11);
assertTrue (dt.day() == 24);
assertTrue (dt.hour() == 12);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.dayOfWeek() == 1);
assertTrue (dt.julianDay() == 0);
// Test that we can represent down to the microsecond.
dt = DateTime(2010, 1, 31, 17, 30, 15, 800, 3);
assertTrue (dt.year() == 2010);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 31);
assertTrue (dt.hour() == 17);
assertTrue (dt.minute() == 30);
assertTrue (dt.second() == 15);
assertTrue (dt.millisecond() == 800);
assertTrue (dt.microsecond() == 3);
}
void DateTimeTest::testGregorian()
{
DateTime dt(1970, 1, 1);
assertTrue (dt.year() == 1970);
assertTrue (dt.month() == 1);
assertTrue (dt.day() == 1);
assertTrue (dt.hour() == 0);
assertTrue (dt.minute() == 0);
assertTrue (dt.second() == 0);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.dayOfWeek() == 4);
assertTrue (dt.julianDay() == 2440587.5);
assertTrue (dt.timestamp() == 0);
dt.assign(2001, 9, 9, 1, 46, 40);
assertTrue (dt.year() == 2001);
assertTrue (dt.month() == 9);
assertTrue (dt.day() == 9);
assertTrue (dt.hour() == 1);
assertTrue (dt.minute() == 46);
assertTrue (dt.second() == 40);
assertTrue (dt.millisecond() == 0);
assertTrue (dt.dayOfWeek() == 0);
assertTrue (dt.timestamp().epochTime() == 1000000000);
assertEqualDelta (dt.julianDay(), 2452161.574074, 0.000001);
}
void DateTimeTest::testConversions()
{
DateTime dt1(2005, 1, 28, 14, 24, 44, 234);
Timestamp ts1 = dt1.timestamp();
DateTime dt2(ts1);
Timestamp ts2 = dt2.timestamp();
DateTime dt3;
dt3 = dt1;
Timestamp ts3 = dt3.timestamp();
DateTime dt4(dt2);
Timestamp ts4 = dt4.timestamp();
assertTrue (ts1 == ts2);
assertTrue (ts2 == ts3);
assertTrue (ts3 == ts4);
assertTrue (dt2.year() == 2005);
assertTrue (dt2.month() == 1);
assertTrue (dt2.day() == 28);
assertTrue (dt2.hour() == 14);
assertTrue (dt2.minute() == 24);
assertTrue (dt2.second() == 44);
assertTrue (dt2.millisecond() == 234);
assertTrue (dt2.dayOfWeek() == 5);
}
void DateTimeTest::testStatics()
{
assertTrue (DateTime::isLeapYear(1984));
assertTrue (DateTime::isLeapYear(1988));
assertTrue (DateTime::isLeapYear(1992));
assertTrue (DateTime::isLeapYear(1996));
assertTrue (DateTime::isLeapYear(2000));
assertTrue (DateTime::isLeapYear(2400));
assertTrue (!DateTime::isLeapYear(1995));
assertTrue (!DateTime::isLeapYear(1998));
assertTrue (!DateTime::isLeapYear(2001));
assertTrue (!DateTime::isLeapYear(1800));
assertTrue (!DateTime::isLeapYear(1900));
assertTrue (DateTime::daysOfMonth(2000, 1) == 31);
assertTrue (DateTime::daysOfMonth(2000, 2) == 29);
assertTrue (DateTime::daysOfMonth(1999, 2) == 28);
}
void DateTimeTest::testCalcs()
{
DateTime dt1(2005, 1, 1);
assertTrue (dt1.dayOfYear() == 1);
assertTrue (dt1.week(DateTime::MONDAY) == 0);
dt1.assign(2005, 1, 3);
assertTrue (dt1.dayOfYear() == 3);
assertTrue (dt1.week(DateTime::MONDAY) == 1);
dt1.assign(2005, 1, 9);
assertTrue (dt1.dayOfYear() == 9);
assertTrue (dt1.week(DateTime::MONDAY) == 1);
dt1.assign(2005, 1, 10);
assertTrue (dt1.dayOfYear() == 10);
assertTrue (dt1.week(DateTime::MONDAY) == 2);
dt1.assign(2005, 2, 1);
assertTrue (dt1.dayOfYear() == 32);
assertTrue (dt1.week(DateTime::MONDAY) == 5);
dt1.assign(2005, 12, 31);
assertTrue (dt1.week(DateTime::MONDAY) == 52);
dt1.assign(2007, 1, 1);
assertTrue (dt1.week(DateTime::MONDAY) == 1);
dt1.assign(2007, 12, 31);
assertTrue (dt1.week(DateTime::MONDAY) == 53);
// Jan 1 is Mon
dt1.assign(2001, 1, 1);
assertTrue (dt1.week() == 1);
dt1.assign(2001, 1, 7);
assertTrue (dt1.week() == 1);
dt1.assign(2001, 1, 8);
assertTrue (dt1.week() == 2);
dt1.assign(2001, 1, 21);
assertTrue (dt1.week() == 3);
dt1.assign(2001, 1, 22);
assertTrue (dt1.week() == 4);
// Jan 1 is Tue
dt1.assign(2002, 1, 1);
assertTrue (dt1.week() == 1);
dt1.assign(2002, 1, 6);
assertTrue (dt1.week() == 1);
dt1.assign(2002, 1, 7);
assertTrue (dt1.week() == 2);
dt1.assign(2002, 1, 20);
assertTrue (dt1.week() == 3);
dt1.assign(2002, 1, 21);
assertTrue (dt1.week() == 4);
// Jan 1 is Wed
dt1.assign(2003, 1, 1);
assertTrue (dt1.week() == 1);
dt1.assign(2003, 1, 5);
assertTrue (dt1.week() == 1);
dt1.assign(2003, 1, 6);
assertTrue (dt1.week() == 2);
dt1.assign(2003, 1, 19);
assertTrue (dt1.week() == 3);
dt1.assign(2003, 1, 20);
assertTrue (dt1.week() == 4);
// Jan 1 is Thu
dt1.assign(2004, 1, 1);
assertTrue (dt1.week() == 1);
dt1.assign(2004, 1, 4);
assertTrue (dt1.week() == 1);
dt1.assign(2004, 1, 5);
assertTrue (dt1.week() == 2);
dt1.assign(2004, 1, 18);
assertTrue (dt1.week() == 3);
dt1.assign(2004, 1, 19);
assertTrue (dt1.week() == 4);
// Jan 1 is Fri
dt1.assign(1999, 1, 1);
assertTrue (dt1.week() == 0);
dt1.assign(1999, 1, 3);
assertTrue (dt1.week() == 0);
dt1.assign(1999, 1, 4);
assertTrue (dt1.week() == 1);
dt1.assign(1999, 1, 17);
assertTrue (dt1.week() == 2);
dt1.assign(1999, 1, 18);
assertTrue (dt1.week() == 3);
// Jan 1 is Sat
dt1.assign(2000, 1, 1);
assertTrue (dt1.week() == 0);
dt1.assign(2000, 1, 2);
assertTrue (dt1.week() == 0);
dt1.assign(2000, 1, 3);
assertTrue (dt1.week() == 1);
dt1.assign(2000, 1, 16);
assertTrue (dt1.week() == 2);
dt1.assign(2000, 1, 17);
assertTrue (dt1.week() == 3);
// Jan 1 is Sun
dt1.assign(1995, 1, 1);
assertTrue (dt1.week() == 0);
dt1.assign(1995, 1, 2);
assertTrue (dt1.week() == 1);
dt1.assign(1995, 1, 3);
assertTrue (dt1.week() == 1);
dt1.assign(1995, 1, 15);
assertTrue (dt1.week() == 2);
dt1.assign(1995, 1, 16);
assertTrue (dt1.week() == 3);
}
void DateTimeTest::testAMPM()
{
DateTime dt1(2005, 1, 1, 0, 15, 30);
assertTrue (dt1.isAM());
assertTrue (!dt1.isPM());
assertTrue (dt1.hourAMPM() == 12);
dt1.assign(2005, 1, 1, 12, 15, 30);
assertTrue (!dt1.isAM());
assertTrue (dt1.isPM());
assertTrue (dt1.hourAMPM() == 12);
dt1.assign(2005, 1, 1, 13, 15, 30);
assertTrue (!dt1.isAM());
assertTrue (dt1.isPM());
assertTrue (dt1.hourAMPM() == 1);
}
void DateTimeTest::testRelational()
{
DateTime dt1(2005, 1, 1, 0, 15, 30);
DateTime dt2(2005, 1, 2, 0, 15, 30);
DateTime dt3(dt1);
assertTrue (dt1 < dt2);
assertTrue (dt1 <= dt2);
assertTrue (dt2 > dt1);
assertTrue (dt2 >= dt1);
assertTrue (dt1 != dt2);
assertTrue (!(dt1 == dt2));
assertTrue (dt1 == dt3);
assertTrue (!(dt1 != dt3));
assertTrue (dt1 >= dt3);
assertTrue (dt1 <= dt3);
assertTrue (!(dt1 > dt3));
assertTrue (!(dt1 < dt3));
static const struct
{
int year;
int month;
int day;
} values[] =
{
{ 1, 1, 1 },
{ 10, 4, 5 },
{ 100, 6, 7 },
{ 1000, 8, 9 },
{ 2000, 1, 31 },
{ 2002, 7, 4 },
{ 2002, 12, 31 },
{ 2003, 1, 1 },
{ 2003, 1, 2 },
{ 2003, 8, 5 },
{ 2003, 8, 6 },
{ 2003, 8, 7 },
{ 2004, 9, 3 },
{ 2004, 9, 4 },
};
const int num_values = sizeof values / sizeof *values;
for (int i = 0; i < num_values; ++i)
{
DateTime v;
const DateTime& V = v;
v.assign(values[i].year, values[i].month, values[i].day);
for (int j = 0; j < num_values; ++j)
{
DateTime u;
const DateTime& U = u;
u.assign(values[j].year, values[j].month, values[j].day);
loop_2_assert (i, j, (j < i) == (U < V));
loop_2_assert (i, j, (j <= i) == (U <= V));
loop_2_assert (i, j, (j >= i) == (U >= V));
loop_2_assert (i, j, (j > i) == (U > V));
}
}
}
void DateTimeTest::testArithmetics()
{
DateTime dt1(2005, 1, 1, 0, 15, 30);
DateTime dt2(2005, 1, 2, 0, 15, 30);
Timespan s = dt2 - dt1;
assertTrue (s.days() == 1);
DateTime dt3 = dt1 + s;
assertTrue (dt3 == dt2);
dt3 -= s;
assertTrue (dt3 == dt1);
dt1 += s;
assertTrue (dt1 == dt2);
static const struct
{
int lineNum; // source line number
int year1; // operand/result date1 year
int month1; // operand/result date1 month
unsigned int day1; // operand/result date1 day
int numDays; // operand/result 'int' number of days
int year2; // operand/result date2 year
int month2; // operand/result date2 month
unsigned int day2; // operand/result date2 day
} data[] =
{
// - - - -first- - - - - - - second - - -
//line no. year month day numDays year month day
//------- ----- ----- ----- ------- ----- ----- -----
{ __LINE__, 1, 1, 1, 1, 1, 1, 2 },
{ __LINE__, 10, 2, 28, 1, 10, 3, 1 },
{ __LINE__, 100, 3, 31, 2, 100, 4, 2 },
{ __LINE__, 1000, 4, 30, 4, 1000, 5, 4 },
{ __LINE__, 1000, 6, 1, -31, 1000, 5, 1 },
{ __LINE__, 1001, 1, 1, -365, 1000, 1, 1 },
{ __LINE__, 1100, 5, 31, 30, 1100, 6, 30 },
{ __LINE__, 1200, 6, 30, 32, 1200, 8, 1 },
{ __LINE__, 1996, 2, 28, 367, 1997, 3, 1 },
{ __LINE__, 1997, 2, 28, 366, 1998, 3, 1 },
{ __LINE__, 1998, 2, 28, 365, 1999, 2, 28 },
{ __LINE__, 1999, 2, 28, 364, 2000, 2, 27 },
{ __LINE__, 1999, 2, 28, 1096, 2002, 2, 28 },
{ __LINE__, 2002, 2, 28, -1096, 1999, 2, 28 },
};
const int num_data = sizeof data / sizeof *data;
for (int di = 0; di < num_data; ++di)
{
const int line = data[di].lineNum;
const int num_days = data[di].numDays;
DateTime x = DateTime(data[di].year1, data[di].month1, data[di].day1);
const DateTime& X = x;
x += Timespan(num_days, 0, 0, 0, 0);
loop_1_assert (line, data[di].year2 == X.year());
loop_1_assert (line, data[di].month2 == X.month());
loop_1_assert (line, data[di].day2 == X.day());
}
DateTime edgeTime(2014, 9, 16, 0, 0, 0, 0, 10);
edgeTime -= Poco::Timespan(11);
assertTrue (edgeTime.year() == 2014);
assertTrue (edgeTime.month() == 9);
assertTrue (edgeTime.day() == 15);
assertTrue (edgeTime.hour() == 23);
assertTrue (edgeTime.minute() == 59);
assertTrue (edgeTime.second() == 59);
assertTrue (edgeTime.millisecond() == 999);
assertTrue (edgeTime.microsecond() == 999);
edgeTime.assign(2014, 9, 15, 23, 59, 59, 999, 968);
edgeTime += Poco::Timespan(11);
assertTrue (edgeTime.year() == 2014);
assertTrue (edgeTime.month() == 9);
assertTrue (edgeTime.day() == 15);
assertTrue (edgeTime.hour() == 23);
assertTrue (edgeTime.minute() == 59);
assertTrue (edgeTime.second() == 59);
assertTrue (edgeTime.millisecond() == 999);
assertTrue (edgeTime.microsecond() == 979);
}
void DateTimeTest::testIncrementDecrement()
{
static const struct
{
int lineNum; // source line number
int year1; // (first) date year
int month1; // (first) date month
unsigned int day1; // (first) date day
int year2; // (second) date year
int month2; // (second) date month
unsigned int day2; // (second) date day
} data[] =
{
// - - - -first- - - - - - - second - - -
//line no. year month day year month day
//------- ----- ----- ----- ----- ----- -----
{ __LINE__, 1, 1, 1, 1, 1, 2 },
{ __LINE__, 10, 2, 28, 10, 3, 1 },
{ __LINE__, 100, 3, 31, 100, 4, 1 },
{ __LINE__, 1000, 4, 30, 1000, 5, 1 },
{ __LINE__, 1100, 5, 31, 1100, 6, 1 },
{ __LINE__, 1200, 6, 30, 1200, 7, 1 },
{ __LINE__, 1300, 7, 31, 1300, 8, 1 },
{ __LINE__, 1400, 8, 31, 1400, 9, 1 },
{ __LINE__, 1500, 9, 30, 1500, 10, 1 },
{ __LINE__, 1600, 10, 31, 1600, 11, 1 },
{ __LINE__, 1700, 11, 30, 1700, 12, 1 },
{ __LINE__, 1800, 12, 31, 1801, 1, 1 },
{ __LINE__, 1996, 2, 28, 1996, 2, 29 },
{ __LINE__, 1997, 2, 28, 1997, 3, 1 },
{ __LINE__, 1998, 2, 28, 1998, 3, 1 },
{ __LINE__, 1999, 2, 28, 1999, 3, 1 },
{ __LINE__, 2000, 2, 28, 2000, 2, 29 },
{ __LINE__, 2001, 2, 28, 2001, 3, 1 },
{ __LINE__, 2004, 2, 28, 2004, 2, 29 },
{ __LINE__, 2100, 2, 28, 2100, 3, 1 },
{ __LINE__, 2400, 2, 28, 2400, 2, 29 },
};
const int num_data = sizeof data / sizeof *data;
int di;
for (di = 0; di < num_data; ++di)
{
const int line = data[di].lineNum;
DateTime x = DateTime(data[di].year1, data[di].month1,
data[di].day1);
// Would do pre-increment of x here.
const DateTime& X = x;
x = x + Timespan(1,0,0,0,0);
DateTime y = x; const DateTime& Y = y;
loop_1_assert (line, data[di].year2 == X.year());
loop_1_assert (line, data[di].month2 == X.month());
loop_1_assert (line, data[di].day2 == X.day());
loop_1_assert (line, data[di].year2 == Y.year());
loop_1_assert (line, data[di].month2 == Y.month());
loop_1_assert (line, data[di].day2 == Y.day());
}
for (di = 0; di < num_data; ++di)
{
const int line = data[di].lineNum;
DateTime x = DateTime(data[di].year1, data[di].month1, data[di].day1);
DateTime x1 = DateTime(data[di].year1, data[di].month1, data[di].day1);
DateTime x2 = DateTime(data[di].year2, data[di].month2, data[di].day2);
DateTime y = x; const DateTime& Y = y;
// Would do post increment of x here.
const DateTime& X = x;
x = x + Timespan(1,0,0,0,0);
loop_1_assert (line, data[di].year2 == X.year());
loop_1_assert (line, data[di].month2 == X.month());
loop_1_assert (line, data[di].day2 == X.day());
loop_1_assert (line, data[di].year1 == Y.year());
loop_1_assert (line, data[di].month1 == Y.month());
loop_1_assert (line, data[di].day1 == Y.day());
}
for (di = 0; di < num_data; ++di)
{
const int line = data[di].lineNum;
DateTime x = DateTime(data[di].year2, data[di].month2, data[di].day2);
const DateTime& X = x;
x = x - Timespan(1,0,0,0,0);
DateTime y = x; DateTime Y = y;
loop_1_assert (line, data[di].year1 == X.year());
loop_1_assert (line, data[di].month1 == X.month());
loop_1_assert (line, data[di].day1 == X.day());
loop_1_assert (line, data[di].year1 == Y.year());
loop_1_assert (line, data[di].month1 == Y.month());
loop_1_assert (line, data[di].day1 == Y.day());
}
for (di = 0; di < num_data; ++di)
{
const int line = data[di].lineNum;
DateTime x1 = DateTime(data[di].year1, data[di].month1, data[di].day1);
DateTime x = DateTime(data[di].year2, data[di].month2, data[di].day2);
DateTime y = x; DateTime Y = y;
const DateTime& X = x;
// would post-decrement x here.
x = x - Timespan(1,0,0,0,0);
loop_1_assert (line, data[di].year1 == X.year());
loop_1_assert (line, data[di].month1 == X.month());
loop_1_assert (line, data[di].day1 == X.day());
loop_1_assert (line, data[di].year2 == Y.year());
loop_1_assert (line, data[di].month2 == Y.month());
loop_1_assert (line, data[di].day2 == Y.day());
}
}
void DateTimeTest::testSwap()
{
DateTime dt1(2005, 1, 1, 0, 15, 30);
DateTime dt2(2005, 1, 2, 0, 15, 30);
DateTime dt3(2005, 1, 1, 0, 15, 30);
DateTime dt4(2005, 1, 2, 0, 15, 30);
dt1.swap(dt2);
assertTrue (dt2 == dt3);
assertTrue (dt1 == dt4);
}
void DateTimeTest::testUsage()
{
DateTime dt1(1776, 7, 4);
assertTrue (dt1.year() == 1776);
assertTrue (dt1.month() == 7);
assertTrue (dt1.day() == 4);
DateTime dt2(dt1);
dt2 += Timespan(6, 0, 0, 0, 0);
assertTrue (dt2.year() == 1776);
assertTrue (dt2.month() == 7);
assertTrue (dt2.day() == 10);
Timespan span = dt2 - dt1;
assertTrue (span.days() == 6);
// TODO - When adding months and years we need to be
// able to specify the end-end convention.
// We cannot do this in POCO at the moment.
}
void DateTimeTest::testSetYearDay()
{
static const struct
{
int d_lineNum; // source line number
int d_year; // year under test
unsigned int d_day; // day-of-year under test
int d_expMonth; // expected month
unsigned int d_expDay; // expected day
} data[] =
{
//line no. year dayOfYr exp. month exp. day
//------- ----- ------- ---------- --------
{ __LINE__, 1, 1, 1, 1 },
{ __LINE__, 1, 2, 1, 2 },
{ __LINE__, 1, 365, 12, 31 },
{ __LINE__, 1996, 1, 1, 1 },
{ __LINE__, 1996, 2, 1, 2 },
{ __LINE__, 1996, 365, 12, 30 },
{ __LINE__, 1996, 366, 12, 31 }
};
const int num_data = sizeof data / sizeof *data;
for (int di = 0; di < num_data; ++di)
{
const int POCO_UNUSED line = data[di].d_lineNum;
const int year = data[di].d_year;
const unsigned int POCO_UNUSED day = data[di].d_day;
const int exp_month = data[di].d_expMonth;
const unsigned int exp_day = data[di].d_expDay;
const DateTime r(year, exp_month, exp_day);
DateTime x;
const DateTime& POCO_UNUSED X = x;
#if 0
// TODO - need to be able to assign a day number in the year
// but POCO is not able to do this.
x.assign(year, day);
// TODO - need to be able to assert with the loop counter
// but cppUnit is not able to do this.
assertTrue (r == x);
assertTrue (day == X.dayOfYear());
#endif
}
static const struct
{
int d_lineNum; // source line number
int d_year; // year under test
int d_day; // day-of-year under test
int d_exp; // expected status
} data2[] =
{
//line no. year dayOfYr expected value
//------- ----- ------- --------------
{ __LINE__, 1, 1, 1 },
{ __LINE__, 1, -1, 0 },
{ __LINE__, 1, 0, 0 },
{ __LINE__, 1, 365, 1 },
{ __LINE__, 1, 366, 0 },
{ __LINE__, 1, 367, 0 },
{ __LINE__, 0, 0, 0 },
{ __LINE__, -1, -1, 0 },
{ __LINE__, 1996, 1, 1 },
{ __LINE__, 1996, 2, 1 },
{ __LINE__, 1996, 32, 1 },
{ __LINE__, 1996, 365, 1 },
{ __LINE__, 1996, 366, 1 },
{ __LINE__, 1996, 367, 0 },
};
const int num_data2 = sizeof data2 / sizeof *data2;
for (int di = 0; di < num_data2; ++di)
{
const int POCO_UNUSED line = data2[di].d_lineNum;
const int POCO_UNUSED year = data2[di].d_year;
const int POCO_UNUSED day = data2[di].d_day;
const int exp = data2[di].d_exp;
DateTime x;
const DateTime& POCO_UNUSED X = x;
if (1 == exp)
{
DateTime r;
const POCO_UNUSED DateTime& r2 = r;
#if 0
r.set(year, day);
#endif
}
}
}
void DateTimeTest::testIsValid()
{
static const struct
{
int d_lineNum; // source line number
int d_year; // year under test
int d_month; // month under test
int d_day; // day under test
bool d_exp; // expected value
} data[] =
{
//line no. year month day expected value
//------- ----- ----- ----- --------------
{ __LINE__, 0, 0, 0, false },
{ __LINE__, 1, 1, 0, false },
{ __LINE__, 1, 0, 1, false },
{ __LINE__, 0, 1, 1, true },
{ __LINE__, 1, 1, -1, false },
{ __LINE__, 1, -1, 1, false },
{ __LINE__, 2004, 1, 32, false },
{ __LINE__, 2004, 2, 30, false },
{ __LINE__, 2004, 3, 32, false },
{ __LINE__, 2004, 4, 31, false },
{ __LINE__, 2004, 5, 32, false },
{ __LINE__, 2004, 6, 31, false },
{ __LINE__, 2004, 7, 32, false },
{ __LINE__, 2004, 8, 32, false },
{ __LINE__, 2004, 9, 31, false },
{ __LINE__, 2004, 10, 32, false },
{ __LINE__, 2004, 11, 31, false },
{ __LINE__, 2004, 12, 32, false },
{ __LINE__, 0, 12, 31, true },
{ __LINE__, 0, 2, 29, true },
{ __LINE__, 1, 1, 1, true },
{ __LINE__, 2010, 1, 2, true },
{ __LINE__, 2011, 2, 5, true },
{ __LINE__, 2012, 3, 10, true },
{ __LINE__, 2013, 4, 17, true },
{ __LINE__, 2014, 5, 23, true },
{ __LINE__, 1600, 2, 29, true },
{ __LINE__, 1700, 2, 29, false },
{ __LINE__, 1800, 2, 29, false },
{ __LINE__, 1900, 2, 29, false },
{ __LINE__, 2000, 2, 29, true },
{ __LINE__, 2100, 2, 29, false },
};
const int num_data = sizeof data / sizeof *data;
for (int di = 0; di < num_data; ++di)
{
const int line = data[di].d_lineNum;
const int year = data[di].d_year;
const int month = data[di].d_month;
const int day = data[di].d_day;
const bool exp = data[di].d_exp;
bool isValid = DateTime::isValid(year, month, day);
loop_1_assert (line, exp == isValid);
}
}
void DateTimeTest::testDayOfWeek()
{
typedef DateTime::DaysOfWeek DOW;
static const struct
{
int d_lineNum; // source line number
int d_year; // year under test
int d_month; // month under test
int d_day; // day under test
DOW d_expDay; // number of days to be added
} data[] =
{
//Line no. year month day expDay
//------- ----- ----- ----- -------
{ __LINE__, 1600, 1, 1, DateTime::SATURDAY },
{ __LINE__, 1600, 1, 2, DateTime::SUNDAY },
{ __LINE__, 1600, 1, 3, DateTime::MONDAY },
{ __LINE__, 1600, 1, 4, DateTime::TUESDAY },
{ __LINE__, 1600, 1, 5, DateTime::WEDNESDAY },
{ __LINE__, 1600, 1, 6, DateTime::THURSDAY },
{ __LINE__, 1600, 1, 7, DateTime::FRIDAY },
{ __LINE__, 1600, 1, 8, DateTime::SATURDAY },
{ __LINE__, 1752, 8, 27, DateTime::SUNDAY },
{ __LINE__, 1752, 8, 28, DateTime::MONDAY },
{ __LINE__, 1752, 8, 29, DateTime::TUESDAY },
{ __LINE__, 1752, 8, 30, DateTime::WEDNESDAY },
{ __LINE__, 1752, 8, 31, DateTime::THURSDAY },
{ __LINE__, 1752, 9, 1, DateTime::FRIDAY },
{ __LINE__, 1752, 9, 2, DateTime::SATURDAY },
{ __LINE__, 1752, 9, 14, DateTime::THURSDAY },
{ __LINE__, 1752, 9, 15, DateTime::FRIDAY },
{ __LINE__, 1752, 9, 16, DateTime::SATURDAY },
{ __LINE__, 1752, 9, 17, DateTime::SUNDAY },
{ __LINE__, 1752, 9, 18, DateTime::MONDAY },
{ __LINE__, 1752, 9, 19, DateTime::TUESDAY },
{ __LINE__, 1999, 12, 28, DateTime::TUESDAY },
{ __LINE__, 1999, 12, 29, DateTime::WEDNESDAY },
{ __LINE__, 1999, 12, 30, DateTime::THURSDAY },
{ __LINE__, 1999, 12, 31, DateTime::FRIDAY },
{ __LINE__, 2000, 1, 1, DateTime::SATURDAY },
{ __LINE__, 2000, 1, 2, DateTime::SUNDAY },
{ __LINE__, 2000, 1, 3, DateTime::MONDAY },
{ __LINE__, 2000, 1, 4, DateTime::TUESDAY },
};
const int num_data = sizeof data / sizeof *data;
for (int di = 0; di < num_data ; ++di)
{
const int line = data[di].d_lineNum;
DateTime x = DateTime(data[di].d_year, data[di].d_month, data[di].d_day);
const DateTime& X = x;
loop_1_assert (line, data[di].d_expDay == X.dayOfWeek());
}
}
void DateTimeTest::testUTC()
{
DateTime dt(2007, 3, 5, 12, 30, 00);
assertTrue (dt.hour() == 12);
dt.makeUTC(3600);
assertTrue (dt.hour() == 11);
dt.makeLocal(3600);
assertTrue (dt.hour() == 12);
}
void DateTimeTest::testLeapSeconds()
{
DateTime dt1(2015, 6, 30, 23, 59, 60);
DateTime dt2(2015, 7, 1, 0, 0, 0);
assertTrue (dt1 == dt2);
}
void DateTimeTest::testTM()
{
time_t now;
time(&now);
tm* pTM = gmtime(&now);
DateTime dt(*pTM);
assertTrue (dt.second() == pTM->tm_sec);
assertTrue (dt.minute() == pTM->tm_min);
assertTrue (dt.hour() == pTM->tm_hour);
assertTrue (dt.day() == pTM->tm_mday);
assertTrue (dt.month() == pTM->tm_mon + 1);
assertTrue (dt.year() == pTM->tm_year + 1900);
assertTrue (dt.dayOfWeek() == pTM->tm_wday);
assertTrue (dt.dayOfYear() == pTM->tm_yday + 1);
}
void DateTimeTest::setUp()
{
}
void DateTimeTest::tearDown()
{
}
CppUnit::Test* DateTimeTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeTest");
CppUnit_addTest(pSuite, DateTimeTest, testTimestamp);
CppUnit_addTest(pSuite, DateTimeTest, testJulian);
CppUnit_addTest(pSuite, DateTimeTest, testGregorian);
CppUnit_addTest(pSuite, DateTimeTest, testConversions);
CppUnit_addTest(pSuite, DateTimeTest, testStatics);
CppUnit_addTest(pSuite, DateTimeTest, testCalcs);
CppUnit_addTest(pSuite, DateTimeTest, testAMPM);
CppUnit_addTest(pSuite, DateTimeTest, testRelational);
CppUnit_addTest(pSuite, DateTimeTest, testArithmetics);
CppUnit_addTest(pSuite, DateTimeTest, testSwap);
CppUnit_addTest(pSuite, DateTimeTest, testUsage);
CppUnit_addTest(pSuite, DateTimeTest, testSetYearDay);
CppUnit_addTest(pSuite, DateTimeTest, testIsValid);
CppUnit_addTest(pSuite, DateTimeTest, testDayOfWeek);
CppUnit_addTest(pSuite, DateTimeTest, testIncrementDecrement);
CppUnit_addTest(pSuite, DateTimeTest, testUTC);
CppUnit_addTest(pSuite, DateTimeTest, testLeapSeconds);
CppUnit_addTest(pSuite, DateTimeTest, testTM);
return pSuite;
}

View File

@@ -0,0 +1,55 @@
//
// DateTimeTest.h
//
// Definition of the DateTimeTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DateTimeTest_INCLUDED
#define DateTimeTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class DateTimeTest: public CppUnit::TestCase
{
public:
DateTimeTest(const std::string& name);
~DateTimeTest();
void testTimestamp();
void testJulian();
void testGregorian();
void testConversions();
void testStatics();
void testCalcs();
void testAMPM();
void testRelational();
void testArithmetics();
void testSwap();
void testUsage();
void testSetYearDay();
void testIsValid();
void testDayOfWeek();
void testIncrementDecrement();
void testUTC();
void testLeapSeconds();
void testTM();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // DateTimeTest_INCLUDED

View File

@@ -0,0 +1,36 @@
//
// DateTimeTestSuite.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DateTimeTestSuite.h"
#include "TimestampTest.h"
#include "ClockTest.h"
#include "TimespanTest.h"
#include "TimezoneTest.h"
#include "DateTimeTest.h"
#include "LocalDateTimeTest.h"
#include "DateTimeFormatterTest.h"
#include "DateTimeParserTest.h"
CppUnit::Test* DateTimeTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DateTimeTestSuite");
pSuite->addTest(TimestampTest::suite());
pSuite->addTest(ClockTest::suite());
pSuite->addTest(TimespanTest::suite());
pSuite->addTest(TimezoneTest::suite());
pSuite->addTest(DateTimeTest::suite());
pSuite->addTest(LocalDateTimeTest::suite());
pSuite->addTest(DateTimeFormatterTest::suite());
pSuite->addTest(DateTimeParserTest::suite());
return pSuite;
}

View File

@@ -0,0 +1,27 @@
//
// DateTimeTestSuite.h
//
// Definition of the DateTimeTestSuite class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DateTimeTestSuite_INCLUDED
#define DateTimeTestSuite_INCLUDED
#include "CppUnit/TestSuite.h"
class DateTimeTestSuite
{
public:
static CppUnit::Test* suite();
};
#endif // DateTimeTestSuite_INCLUDED

View File

@@ -0,0 +1,104 @@
//
// DigestStreamTest.cpp
//
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DigestStreamTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/DigestStream.h"
#include "Poco/MD5Engine.h"
#include <sstream>
using Poco::DigestInputStream;
using Poco::DigestOutputStream;
using Poco::DigestEngine;
using Poco::MD5Engine;
DigestStreamTest::DigestStreamTest(const std::string& name): CppUnit::TestCase(name)
{
}
DigestStreamTest::~DigestStreamTest()
{
}
void DigestStreamTest::testInputStream()
{
std::istringstream istr("abcdefghijklmnopqrstuvwxyz");
MD5Engine md5;
DigestInputStream ds(md5, istr);
std::string s;
ds >> s;
assertTrue (DigestEngine::digestToHex(md5.digest()) == "c3fcd3d76192e4007dfb496cca67e13b");
assertTrue (s == "abcdefghijklmnopqrstuvwxyz");
}
void DigestStreamTest::testOutputStream1()
{
MD5Engine md5;
DigestOutputStream ds(md5);
ds << "abcdefghijklmnopqrstuvwxyz";
ds.close();
assertTrue (DigestEngine::digestToHex(md5.digest()) == "c3fcd3d76192e4007dfb496cca67e13b");
ds << "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ds << "abcdefghijklmnopqrstuvwxyz0123456789";
ds.close();
assertTrue (DigestEngine::digestToHex(md5.digest()) == "d174ab98d277d9f5a5611c2c9f419d9f");
}
void DigestStreamTest::testOutputStream2()
{
MD5Engine md5;
std::ostringstream ostr;
DigestOutputStream ds(md5, ostr);
ds << "abcdefghijklmnopqrstuvwxyz";
ds.close();
assertTrue (DigestEngine::digestToHex(md5.digest()) == "c3fcd3d76192e4007dfb496cca67e13b");
assertTrue (ostr.str() == "abcdefghijklmnopqrstuvwxyz");
}
void DigestStreamTest::testToFromHex()
{
std::string digest("c3fcd3d76192e4007dfb496cca67e13b");
Poco::DigestEngine::Digest dig = DigestEngine::digestFromHex(digest);
std::string digest2 = DigestEngine::digestToHex(dig);
assertTrue (digest == digest2);
}
void DigestStreamTest::setUp()
{
}
void DigestStreamTest::tearDown()
{
}
CppUnit::Test* DigestStreamTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DigestStreamTest");
CppUnit_addTest(pSuite, DigestStreamTest, testInputStream);
CppUnit_addTest(pSuite, DigestStreamTest, testOutputStream1);
CppUnit_addTest(pSuite, DigestStreamTest, testOutputStream2);
CppUnit_addTest(pSuite, DigestStreamTest, testToFromHex);
return pSuite;
}

View File

@@ -0,0 +1,41 @@
//
// DigestStreamTest.h
//
// Definition of the DigestStreamTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DigestStreamTest_INCLUDED
#define DigestStreamTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class DigestStreamTest: public CppUnit::TestCase
{
public:
DigestStreamTest(const std::string& name);
~DigestStreamTest();
void testInputStream();
void testOutputStream1();
void testOutputStream2();
void testToFromHex();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // DigestStreamTest_INCLUDED

View File

@@ -0,0 +1,205 @@
//
// DirectoryIteratorsTest.cpp
//
// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DirectoryIteratorsTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/SortedDirectoryIterator.h"
#include "Poco/RecursiveDirectoryIterator.h"
#include "Poco/FileStream.h"
#include <iostream>
using namespace Poco;
DirectoryIteratorsTest::DirectoryIteratorsTest(const std::string& name):
CppUnit::TestCase(name)
{
}
DirectoryIteratorsTest::~DirectoryIteratorsTest()
{
}
void DirectoryIteratorsTest::testDirectoryIterator()
{
Path p = path();
DirectoryIterator dirIterator(p);
DirectoryIterator end;
std::vector<std::string> result;
std::string file;
while (dirIterator != end)
{
file = dirIterator->path();
++dirIterator;
result.push_back(file);
}
assertEquals(7, (long) result.size());
}
void DirectoryIteratorsTest::testSortedDirectoryIterator()
{
Path p = path();
SortedDirectoryIterator dirIterator(p);
SortedDirectoryIterator end;
std::vector<std::string> result;
std::string file;
while (dirIterator != end)
{
file = Path(dirIterator->path()).getFileName();
++dirIterator;
result.push_back(file);
}
assertEquals(7, (long) result.size());
assertEquals("first", result[0]);
assertEquals("1", result[1]);
assertEquals("2", result[2]);
assertEquals("A", result[3]);
assertEquals("B", result[4]);
assertEquals("c", result[5]);
assertEquals("d", result[6]);
}
void DirectoryIteratorsTest::testSimpleRecursiveDirectoryIterator()
{
Path p = path();
SimpleRecursiveDirectoryIterator dirIterator(p);
SimpleRecursiveDirectoryIterator end;
std::vector<std::string> result;
std::string file;
while (dirIterator != end)
{
file = dirIterator->path();
++dirIterator;
result.push_back(file);
}
assertEquals(20, (long) result.size());
}
void DirectoryIteratorsTest::testSiblingsFirstRecursiveDirectoryIterator()
{
Path p = path();
SiblingsFirstRecursiveDirectoryIterator dirIterator(p);
SiblingsFirstRecursiveDirectoryIterator end;
std::vector<std::string> result;
std::string file;
while (dirIterator != end)
{
file = dirIterator->path();
++dirIterator;
result.push_back(file);
}
assertEquals(20, (long) result.size());
}
void DirectoryIteratorsTest::setUp()
{
File d(path());
if (d.exists()) d.remove(true);
/*
Build Directory Tree like this:
DirectoryIteratorsTest
|-- 1
|-- 2
|-- A
|-- B
|-- c
|-- d
`-- first
|-- 1
|-- 2
|-- A
|-- B
|-- c
|-- d
`-- second
|-- 1
|-- 2
|-- A
|-- B
|-- c
`-- d
2 directories, 18 files
*/
Path p = path();
createSubdir(p);
p.pushDirectory("first");
createSubdir(p);
p.pushDirectory("second");
createSubdir(p);
}
void DirectoryIteratorsTest::createSubdir(Path& p)
{
File d(p);
d.createDirectories();
FileStream f1(p.toString() + "d");
FileStream f2(p.toString() + "1");
FileStream f3(p.toString() + "A");
FileStream f4(p.toString() + "2");
FileStream f5(p.toString() + "B");
FileStream f6(p.toString() + "c");
}
void DirectoryIteratorsTest::tearDown()
{
try
{
File d(path());
d.remove(true);
}
catch (...)
{
}
}
Poco::Path DirectoryIteratorsTest::path() const
{
Path p(Path::current());
p.pushDirectory("DirectoryIteratorsTest");
return p;
}
CppUnit::Test* DirectoryIteratorsTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DirectoryIteratorsTest");
CppUnit_addTest(pSuite, DirectoryIteratorsTest, testDirectoryIterator);
CppUnit_addTest(pSuite, DirectoryIteratorsTest, testSortedDirectoryIterator);
CppUnit_addTest(pSuite, DirectoryIteratorsTest, testSimpleRecursiveDirectoryIterator);
CppUnit_addTest(pSuite, DirectoryIteratorsTest, testSiblingsFirstRecursiveDirectoryIterator);
return pSuite;
}

View File

@@ -0,0 +1,46 @@
//
// DirectoryIteratorsTest.h
//
// Definition of the DirectoryIteratorsTest class.
//
// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DirectoryIteratorsTest_INCLUDED
#define DirectoryIteratorsTest_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Path.h"
#include "CppUnit/TestCase.h"
class DirectoryIteratorsTest: public CppUnit::TestCase
{
public:
DirectoryIteratorsTest(const std::string& name);
~DirectoryIteratorsTest();
void testDirectoryIterator();
void testSortedDirectoryIterator();
void testSimpleRecursiveDirectoryIterator();
void testSiblingsFirstRecursiveDirectoryIterator();
void setUp();
void tearDown();
static CppUnit::Test* suite();
protected:
Poco::Path path() const;
void createSubdir(Poco::Path& p);
private:
};
#endif // DirectoryIteratorsTest_INCLUDED

View File

@@ -0,0 +1,300 @@
//
// DirectoryWatcherTest.cpp
//
// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DirectoryWatcherTest.h"
#ifndef POCO_NO_INOTIFY
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/DirectoryWatcher.h"
#include "Poco/Delegate.h"
#include "Poco/FileStream.h"
using Poco::DirectoryWatcher;
DirectoryWatcherTest::DirectoryWatcherTest(const std::string& name):
CppUnit::TestCase(name),
_error(false)
{
}
DirectoryWatcherTest::~DirectoryWatcherTest()
{
}
void DirectoryWatcherTest::testAdded()
{
DirectoryWatcher dw(path().toString(), DirectoryWatcher::DW_FILTER_ENABLE_ALL, 2);
dw.itemAdded += Poco::delegate(this, &DirectoryWatcherTest::onItemAdded);
dw.itemRemoved += Poco::delegate(this, &DirectoryWatcherTest::onItemRemoved);
dw.itemModified += Poco::delegate(this, &DirectoryWatcherTest::onItemModified);
dw.itemMovedFrom += Poco::delegate(this, &DirectoryWatcherTest::onItemMovedFrom);
dw.itemMovedTo += Poco::delegate(this, &DirectoryWatcherTest::onItemMovedTo);
Poco::Thread::sleep(1000);
Poco::Path p(path());
p.setFileName("test.txt");
Poco::FileOutputStream fos(p.toString());
fos << "Hello, world!";
fos.close();
Poco::Thread::sleep(2000*dw.scanInterval());
assertTrue (_events.size() >= 1);
assertTrue (_events[0].callback == "onItemAdded");
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
assertTrue (_events[0].type == DirectoryWatcher::DW_ITEM_ADDED);
assertTrue (!_error);
}
void DirectoryWatcherTest::testRemoved()
{
Poco::Path p(path());
p.setFileName("test.txt");
Poco::FileOutputStream fos(p.toString());
fos << "Hello, world!";
fos.close();
DirectoryWatcher dw(path().toString(), DirectoryWatcher::DW_FILTER_ENABLE_ALL, 2);
dw.itemAdded += Poco::delegate(this, &DirectoryWatcherTest::onItemAdded);
dw.itemRemoved += Poco::delegate(this, &DirectoryWatcherTest::onItemRemoved);
dw.itemModified += Poco::delegate(this, &DirectoryWatcherTest::onItemModified);
dw.itemMovedFrom += Poco::delegate(this, &DirectoryWatcherTest::onItemMovedFrom);
dw.itemMovedTo += Poco::delegate(this, &DirectoryWatcherTest::onItemMovedTo);
Poco::Thread::sleep(1000);
Poco::File f(p.toString());
f.remove();
Poco::Thread::sleep(2000*dw.scanInterval());
assertTrue (_events.size() >= 1);
assertTrue (_events[0].callback == "onItemRemoved");
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
assertTrue (_events[0].type == DirectoryWatcher::DW_ITEM_REMOVED);
assertTrue (!_error);
}
void DirectoryWatcherTest::testModified()
{
Poco::Path p(path());
p.setFileName("test.txt");
Poco::FileOutputStream fos(p.toString());
fos << "Hello, world!";
fos.close();
DirectoryWatcher dw(path().toString(), DirectoryWatcher::DW_FILTER_ENABLE_ALL, 2);
dw.itemAdded += Poco::delegate(this, &DirectoryWatcherTest::onItemAdded);
dw.itemRemoved += Poco::delegate(this, &DirectoryWatcherTest::onItemRemoved);
dw.itemModified += Poco::delegate(this, &DirectoryWatcherTest::onItemModified);
dw.itemMovedFrom += Poco::delegate(this, &DirectoryWatcherTest::onItemMovedFrom);
dw.itemMovedTo += Poco::delegate(this, &DirectoryWatcherTest::onItemMovedTo);
Poco::Thread::sleep(1000);
Poco::FileOutputStream fos2(p.toString(), std::ios::app);
fos2 << "Again!";
fos2.close();
Poco::Thread::sleep(2000*dw.scanInterval());
assertTrue (_events.size() >= 1);
assertTrue (_events[0].callback == "onItemModified");
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
assertTrue (_events[0].type == DirectoryWatcher::DW_ITEM_MODIFIED);
assertTrue (!_error);
}
void DirectoryWatcherTest::testMoved()
{
Poco::Path p(path());
p.setFileName("test.txt");
Poco::FileOutputStream fos(p.toString());
fos << "Hello, world!";
fos.close();
DirectoryWatcher dw(path().toString(), DirectoryWatcher::DW_FILTER_ENABLE_ALL, 2);
dw.itemAdded += Poco::delegate(this, &DirectoryWatcherTest::onItemAdded);
dw.itemRemoved += Poco::delegate(this, &DirectoryWatcherTest::onItemRemoved);
dw.itemModified += Poco::delegate(this, &DirectoryWatcherTest::onItemModified);
dw.itemMovedFrom += Poco::delegate(this, &DirectoryWatcherTest::onItemMovedFrom);
dw.itemMovedTo += Poco::delegate(this, &DirectoryWatcherTest::onItemMovedTo);
Poco::Thread::sleep(1000);
Poco::Path p2(path());
p2.setFileName("test2.txt");
Poco::File f(p.toString());
f.renameTo(p2.toString());
Poco::Thread::sleep(2000*dw.scanInterval());
if (dw.supportsMoveEvents())
{
assertTrue (_events.size() >= 2);
assertTrue (
(_events[0].callback == "onItemMovedFrom" && _events[1].callback == "onItemMovedTo") ||
(_events[1].callback == "onItemMovedFrom" && _events[0].callback == "onItemMovedTo")
);
assertTrue (
(Poco::Path(_events[0].path).getFileName() == "test.txt" && Poco::Path(_events[1].path).getFileName() == "test2.txt") ||
(Poco::Path(_events[1].path).getFileName() == "test.txt" && Poco::Path(_events[0].path).getFileName() == "test2.txt")
);
assertTrue (
(_events[0].type == DirectoryWatcher::DW_ITEM_MOVED_FROM && _events[1].type == DirectoryWatcher::DW_ITEM_MOVED_TO) ||
(_events[1].type == DirectoryWatcher::DW_ITEM_MOVED_FROM && _events[0].type == DirectoryWatcher::DW_ITEM_MOVED_TO)
);
}
else
{
assertTrue (_events.size() >= 2);
assertTrue (
(_events[0].callback == "onItemAdded" && _events[1].callback == "onItemRemoved") ||
(_events[1].callback == "onItemAdded" && _events[0].callback == "onItemRemoved")
);
assertTrue (
(Poco::Path(_events[0].path).getFileName() == "test.txt" && Poco::Path(_events[1].path).getFileName() == "test2.txt") ||
(Poco::Path(_events[1].path).getFileName() == "test.txt" && Poco::Path(_events[0].path).getFileName() == "test2.txt")
);
assertTrue (
(_events[0].type == DirectoryWatcher::DW_ITEM_ADDED && _events[1].type == DirectoryWatcher::DW_ITEM_REMOVED) ||
(_events[1].type == DirectoryWatcher::DW_ITEM_ADDED && _events[0].type == DirectoryWatcher::DW_ITEM_REMOVED)
);
}
assertTrue (!_error);
}
void DirectoryWatcherTest::setUp()
{
_error = false;
_events.clear();
try
{
Poco::File d(path().toString());
d.remove(true);
}
catch (...)
{
}
Poco::File d(path().toString());
d.createDirectories();
}
void DirectoryWatcherTest::tearDown()
{
try
{
Poco::File d(path().toString());
d.remove(true);
}
catch (...)
{
}
}
void DirectoryWatcherTest::onItemAdded(const Poco::DirectoryWatcher::DirectoryEvent& ev)
{
DirEvent de;
de.callback = "onItemAdded";
de.path = ev.item.path();
de.type = ev.event;
_events.push_back(de);
}
void DirectoryWatcherTest::onItemRemoved(const Poco::DirectoryWatcher::DirectoryEvent& ev)
{
DirEvent de;
de.callback = "onItemRemoved";
de.path = ev.item.path();
de.type = ev.event;
_events.push_back(de);
}
void DirectoryWatcherTest::onItemModified(const Poco::DirectoryWatcher::DirectoryEvent& ev)
{
DirEvent de;
de.callback = "onItemModified";
de.path = ev.item.path();
de.type = ev.event;
_events.push_back(de);
}
void DirectoryWatcherTest::onItemMovedFrom(const Poco::DirectoryWatcher::DirectoryEvent& ev)
{
DirEvent de;
de.callback = "onItemMovedFrom";
de.path = ev.item.path();
de.type = ev.event;
_events.push_back(de);
}
void DirectoryWatcherTest::onItemMovedTo(const Poco::DirectoryWatcher::DirectoryEvent& ev)
{
DirEvent de;
de.callback = "onItemMovedTo";
de.path = ev.item.path();
de.type = ev.event;
_events.push_back(de);
}
void DirectoryWatcherTest::onError(const Poco::Exception& exc)
{
_error = true;
}
Poco::Path DirectoryWatcherTest::path() const
{
Poco::Path p(Poco::Path::current());
p.pushDirectory("DirectoryWatcherTest");
return p;
}
CppUnit::Test* DirectoryWatcherTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DirectoryWatcherTest");
CppUnit_addTest(pSuite, DirectoryWatcherTest, testAdded);
CppUnit_addTest(pSuite, DirectoryWatcherTest, testRemoved);
CppUnit_addTest(pSuite, DirectoryWatcherTest, testModified);
CppUnit_addTest(pSuite, DirectoryWatcherTest, testMoved);
return pSuite;
}
#endif // POCO_NO_INOTIFY

View File

@@ -0,0 +1,71 @@
//
// DirectoryWatcherTest.h
//
// Definition of the DirectoryWatcherTest class.
//
// Copyright (c) 2012, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DirectoryWatcherTest_INCLUDED
#define DirectoryWatcherTest_INCLUDED
#include "Poco/Foundation.h"
#ifndef POCO_NO_INOTIFY
#include "Poco/DirectoryWatcher.h"
#include "Poco/Path.h"
#include "CppUnit/TestCase.h"
class DirectoryWatcherTest: public CppUnit::TestCase
{
public:
DirectoryWatcherTest(const std::string& name);
~DirectoryWatcherTest();
void testAdded();
void testRemoved();
void testModified();
void testMoved();
void setUp();
void tearDown();
static CppUnit::Test* suite();
protected:
void onItemAdded(const Poco::DirectoryWatcher::DirectoryEvent& ev);
void onItemRemoved(const Poco::DirectoryWatcher::DirectoryEvent& ev);
void onItemModified(const Poco::DirectoryWatcher::DirectoryEvent& ev);
void onItemMovedFrom(const Poco::DirectoryWatcher::DirectoryEvent& ev);
void onItemMovedTo(const Poco::DirectoryWatcher::DirectoryEvent& ev);
void onError(const Poco::Exception& exc);
Poco::Path path() const;
private:
struct DirEvent
{
Poco::DirectoryWatcher::DirectoryEventType type;
std::string callback;
std::string path;
};
std::vector<DirEvent> _events;
bool _error;
};
#endif // POCO_NO_INOTIFY
#endif // DirectoryWatcherTest_INCLUDED

View File

@@ -0,0 +1,17 @@
//
// Driver.cpp
//
// Console-based test driver.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "CppUnit/TestRunner.h"
#include "FoundationTestSuite.h"
CppUnitMain(FoundationTestSuite)

View File

@@ -0,0 +1,33 @@
//
// DummyDelegate.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DummyDelegate.h"
#include "Poco/Exception.h"
DummyDelegate::DummyDelegate() {}
DummyDelegate::~DummyDelegate() {}
void DummyDelegate::onSimple(const void* pSender, int& i)
{
if (i != 0)
{
throw Poco::InvalidArgumentException();
}
i++;
}
void DummyDelegate::onSimple2(const void* pSender, int& i)
{
if (i != 1)
{
throw Poco::InvalidArgumentException();
}
i++;
}

View File

@@ -0,0 +1,28 @@
//
// DummyDelegate.h
//
// Definition of DummyDelegate class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DummyDelegate_INCLUDED
#define DummyDelegate_INCLUDED
class DummyDelegate
{
public:
DummyDelegate();
virtual ~DummyDelegate();
void onSimple(const void* pSender, int& i);
void onSimple2(const void* pSender, int& i);
};
#endif // DummyDelegate_INCLUDED

View File

@@ -0,0 +1,116 @@
//
// DynamicFactoryTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DynamicFactoryTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/DynamicFactory.h"
#include "Poco/Exception.h"
#include <memory>
using Poco::DynamicFactory;
using Poco::Instantiator;
namespace
{
class Base
{
public:
Base()
{
}
virtual ~Base()
{
}
};
class A: public Base
{
};
class B: public Base
{
};
}
DynamicFactoryTest::DynamicFactoryTest(const std::string& name): CppUnit::TestCase(name)
{
}
DynamicFactoryTest::~DynamicFactoryTest()
{
}
void DynamicFactoryTest::testDynamicFactory()
{
DynamicFactory<Base> dynFactory;
dynFactory.registerClass<A>("A");
dynFactory.registerClass<B>("B");
assertTrue (dynFactory.isClass("A"));
assertTrue (dynFactory.isClass("B"));
assertTrue (!dynFactory.isClass("C"));
std::unique_ptr<A> a(dynamic_cast<A*>(dynFactory.createInstance("A")));
std::unique_ptr<B> b(dynamic_cast<B*>(dynFactory.createInstance("B")));
assertNotNull(a.get());
assertNotNull(b.get());
try
{
dynFactory.registerClass<A>("A");
fail("already registered - must throw");
}
catch (Poco::ExistsException&)
{
}
dynFactory.unregisterClass("B");
assertTrue (dynFactory.isClass("A"));
assertTrue (!dynFactory.isClass("B"));
try
{
std::unique_ptr<B> b(dynamic_cast<B*>(dynFactory.createInstance("B")));
fail("unregistered - must throw");
}
catch (Poco::NotFoundException&)
{
}
}
void DynamicFactoryTest::setUp()
{
}
void DynamicFactoryTest::tearDown()
{
}
CppUnit::Test* DynamicFactoryTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DynamicFactoryTest");
CppUnit_addTest(pSuite, DynamicFactoryTest, testDynamicFactory);
return pSuite;
}

View File

@@ -0,0 +1,38 @@
//
// DynamicFactoryTest.h
//
// Definition of the DynamicFactoryTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DynamicFactoryTest_INCLUDED
#define DynamicFactoryTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class DynamicFactoryTest: public CppUnit::TestCase
{
public:
DynamicFactoryTest(const std::string& name);
~DynamicFactoryTest();
void testDynamicFactory();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // DynamicFactoryTest_INCLUDED

View File

@@ -0,0 +1,22 @@
//
// DynamicTestSuite.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "DynamicTestSuite.h"
#include "VarTest.h"
CppUnit::Test* DynamicTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("DynamicTestSuite");
pSuite->addTest(VarTest::suite());
return pSuite;
}

View File

@@ -0,0 +1,27 @@
//
// DynamicTestSuite.h
//
// Definition of the DynamicTestSuite class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef DynamicTestSuite_INCLUDED
#define DynamicTestSuite_INCLUDED
#include "CppUnit/TestSuite.h"
class DynamicTestSuite
{
public:
static CppUnit::Test* suite();
};
#endif // DynamicTestSuite_INCLUDED

View File

@@ -0,0 +1,25 @@
//
// EventTestSuite.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "EventTestSuite.h"
#include "FIFOEventTest.h"
#include "BasicEventTest.h"
#include "PriorityEventTest.h"
CppUnit::Test* EventTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("EventTestSuite");
pSuite->addTest(BasicEventTest::suite());
pSuite->addTest(PriorityEventTest::suite());
pSuite->addTest(FIFOEventTest::suite());
return pSuite;
}

View File

@@ -0,0 +1,27 @@
//
// EventTestSuite.h
//
// Definition of the EventTestSuite class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef EventTestSuite_INCLUDED
#define EventTestSuite_INCLUDED
#include "CppUnit/TestSuite.h"
class EventTestSuite
{
public:
static CppUnit::Test* suite();
};
#endif // EventTestSuite_INCLUDED

View File

@@ -0,0 +1,228 @@
//
// ExpireCacheTest.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ExpireCacheTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Exception.h"
#include "Poco/ExpireCache.h"
#include "Poco/AccessExpireCache.h"
#include "Poco/Bugcheck.h"
#include "Poco/Thread.h"
using namespace Poco;
#define DURSLEEP 250
#define DURHALFSLEEP DURSLEEP / 2
#define DURWAIT 300
ExpireCacheTest::ExpireCacheTest(const std::string& name): CppUnit::TestCase(name)
{
}
ExpireCacheTest::~ExpireCacheTest()
{
}
void ExpireCacheTest::testClear()
{
ExpireCache<int, int> aCache(DURSLEEP);
aCache.add(1, 2);
aCache.add(3, 4);
aCache.add(5, 6);
assertTrue (aCache.has(1));
assertTrue (aCache.has(3));
assertTrue (aCache.has(5));
assertTrue (*aCache.get(1) == 2);
assertTrue (*aCache.get(3) == 4);
assertTrue (*aCache.get(5) == 6);
aCache.clear();
assertTrue (!aCache.has(1));
assertTrue (!aCache.has(3));
assertTrue (!aCache.has(5));
}
void ExpireCacheTest::testExpire0()
{
try
{
ExpireCache<int, int> aCache(24);
failmsg("cache expire lower than 25 is illegal, test should fail");
}
catch (Poco::InvalidArgumentException&)
{
}
}
void ExpireCacheTest::testExpireN()
{
// 3-1 represents the cache sorted by age, elements get replaced at the end of the list
// 3-1|5 -> 5 gets removed
ExpireCache<int, int> aCache(DURSLEEP);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
SharedPtr<int> tmp = aCache.get(1);
assertTrue (!tmp.isNull());
assertTrue (*tmp == 2);
assertTrue (aCache.size() == 1);
Thread::sleep(DURWAIT);
assertTrue (aCache.size() == 0);
assertTrue (!aCache.has(1));
// tmp must still be valid, access it
assertTrue (*tmp == 2);
tmp = aCache.get(1);
assertTrue (!tmp);
aCache.add(1, 2); // 1
Thread::sleep(DURHALFSLEEP);
aCache.add(3, 4); // 3-1
assertTrue (aCache.has(1));
assertTrue (aCache.has(3));
tmp = aCache.get(1);
SharedPtr<int> tmp2 = aCache.get(3);
assertTrue (*tmp == 2);
assertTrue (*tmp2 == 4);
Thread::sleep(DURHALFSLEEP+25); //3|1
assertTrue (!aCache.has(1));
assertTrue (aCache.has(3));
assertTrue (*tmp == 2); // 1-3
assertTrue (*tmp2 == 4); // 3-1
tmp2 = aCache.get(3);
assertTrue (*tmp2 == 4);
Thread::sleep(DURHALFSLEEP+25); //3|1
assertTrue (!aCache.has(3));
assertTrue (*tmp2 == 4);
tmp = aCache.get(1);
tmp2 = aCache.get(3);
assertTrue (!tmp);
assertTrue (!tmp2);
// removing illegal entries should work too
aCache.remove(666);
aCache.clear();
assertTrue (!aCache.has(5));
assertTrue (!aCache.has(3));
}
void ExpireCacheTest::testDuplicateAdd()
{
ExpireCache<int, int> aCache(DURSLEEP);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
assertTrue (*aCache.get(1) == 2);
aCache.add(1, 3);
assertTrue (aCache.has(1));
assertTrue (*aCache.get(1) == 3);
}
void ExpireCacheTest::testAccessExpireN()
{
// 3-1 represents the cache sorted by age, elements get replaced at the end of the list
// 3-1|5 -> 5 gets removed
AccessExpireCache<int, int> aCache(DURSLEEP);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
SharedPtr<int> tmp = aCache.get(1);
assertTrue (!tmp.isNull());
assertTrue (*tmp == 2);
assertTrue (aCache.size() == 1);
Thread::sleep(DURWAIT);
assertTrue (aCache.size() == 0);
assertTrue (!aCache.has(1));
// tmp must still be valid, access it
assertTrue (*tmp == 2);
tmp = aCache.get(1);
assertTrue (!tmp);
aCache.add(1, 2); // 1
Thread::sleep(DURHALFSLEEP);
aCache.add(3, 4); // 3-1
assertTrue (aCache.has(1));
assertTrue (aCache.has(3));
Thread::sleep(DURHALFSLEEP+50); //3|1
assertTrue (!aCache.has(1));
assertTrue (*aCache.get(3) == 4);
Thread::sleep(DURHALFSLEEP+25); //3|1
assertTrue (*aCache.get(3) == 4);
// removing illegal entries should work too
aCache.remove(666);
aCache.clear();
assertTrue (!aCache.has(5));
assertTrue (!aCache.has(3));
}
void ExpireCacheTest::testExpireWithHas()
{
// 3-1 represents the cache sorted by age, elements get replaced at the end of the list
// 3-1|5 -> 5 gets removed
ExpireCache<int, int> aCache(DURSLEEP);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
Thread::sleep(DURWAIT);
assertTrue (!aCache.has(1));
}
void ExpireCacheTest::testAccessExpireGet()
{
AccessExpireCache<int, int> aCache(DURSLEEP);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
SharedPtr<int> tmp = aCache.get(1);
assertTrue (!tmp.isNull());
assertTrue (*tmp == 2);
assertTrue (aCache.size() == 1);
Thread::sleep(DURWAIT);
tmp = aCache.get(1);
assertTrue (tmp.isNull());
}
void ExpireCacheTest::setUp()
{
}
void ExpireCacheTest::tearDown()
{
}
CppUnit::Test* ExpireCacheTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ExpireCacheTest");
CppUnit_addTest(pSuite, ExpireCacheTest, testClear);
CppUnit_addTest(pSuite, ExpireCacheTest, testExpire0);
CppUnit_addTest(pSuite, ExpireCacheTest, testExpireN);
CppUnit_addTest(pSuite, ExpireCacheTest, testDuplicateAdd);
CppUnit_addTest(pSuite, ExpireCacheTest, testAccessExpireN);
CppUnit_addTest(pSuite, ExpireCacheTest, testExpireWithHas);
CppUnit_addTest(pSuite, ExpireCacheTest, testAccessExpireGet);
return pSuite;
}

View File

@@ -0,0 +1,40 @@
//
// ExpireCacheTest.h
//
// Tests for ExpireCache
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ExpireCacheTest_INCLUDED
#define ExpireCacheTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ExpireCacheTest: public CppUnit::TestCase
{
public:
ExpireCacheTest(const std::string& name);
~ExpireCacheTest();
void testClear();
void testDuplicateAdd();
void testExpire0();
void testExpireN();
void testAccessExpireN();
void testExpireWithHas();
void testAccessExpireGet();
void setUp();
void tearDown();
static CppUnit::Test* suite();
};
#endif // ExpireCacheTest_INCLUDED

View File

@@ -0,0 +1,346 @@
//
// ExpireLRUCacheTest.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "ExpireLRUCacheTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Exception.h"
#include "Poco/ExpireLRUCache.h"
#include "Poco/AccessExpireLRUCache.h"
#include "Poco/Bugcheck.h"
#include "Poco/Thread.h"
using namespace Poco;
#define DURSLEEP 250
#define DURHALFSLEEP DURSLEEP / 2
#define DURWAIT 300
ExpireLRUCacheTest::ExpireLRUCacheTest(const std::string& name): CppUnit::TestCase(name)
{
}
ExpireLRUCacheTest::~ExpireLRUCacheTest()
{
}
void ExpireLRUCacheTest::testClear()
{
ExpireLRUCache<int, int> aCache(DURSLEEP);
aCache.add(1, 2);
aCache.add(3, 4);
aCache.add(5, 6);
assertTrue (aCache.has(1));
assertTrue (aCache.has(3));
assertTrue (aCache.has(5));
assertTrue (*aCache.get(1) == 2);
assertTrue (*aCache.get(3) == 4);
assertTrue (*aCache.get(5) == 6);
aCache.clear();
assertTrue (!aCache.has(1));
assertTrue (!aCache.has(3));
assertTrue (!aCache.has(5));
}
void ExpireLRUCacheTest::testExpire0()
{
try
{
ExpireLRUCache<int, int> aCache(1024, 24);
failmsg("cache expire lower than 25 is illegal, test should fail");
}
catch (Poco::InvalidArgumentException&)
{
}
}
void ExpireLRUCacheTest::testExpireN()
{
// 3-1 represents the cache sorted by age, elements get replaced at the end of the list
// 3-1|5 -> 5 gets removed
ExpireLRUCache<int, int> aCache(3, DURSLEEP);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
SharedPtr<int> tmp = aCache.get(1);
assertTrue (!tmp.isNull());
assertTrue (*tmp == 2);
Thread::sleep(DURWAIT);
assertTrue (!aCache.has(1));
// tmp must still be valid, access it
assertTrue (*tmp == 2);
tmp = aCache.get(1);
assertTrue (!tmp);
aCache.add(1, 2); // 1
Thread::sleep(DURHALFSLEEP);
aCache.add(3, 4); // 3-1
assertTrue (aCache.has(1));
assertTrue (aCache.has(3));
tmp = aCache.get(1);
SharedPtr<int> tmp2 = aCache.get(3);
assertTrue (*tmp == 2);
assertTrue (*tmp2 == 4);
Thread::sleep(DURHALFSLEEP+25); //3|1
assertTrue (!aCache.has(1));
assertTrue (aCache.has(3));
assertTrue (*tmp == 2); // 1-3
assertTrue (*tmp2 == 4); // 3-1
tmp2 = aCache.get(3);
assertTrue (*tmp2 == 4);
Thread::sleep(DURHALFSLEEP+25); //3|1
assertTrue (!aCache.has(3));
assertTrue (*tmp2 == 4);
tmp = aCache.get(1);
tmp2 = aCache.get(3);
assertTrue (!tmp);
assertTrue (!tmp2);
// removing illegal entries should work too
aCache.remove(666);
aCache.clear();
assertTrue (!aCache.has(5));
assertTrue (!aCache.has(3));
}
void ExpireLRUCacheTest::testAccessExpireN()
{
// 3-1 represents the cache sorted by age, elements get replaced at the end of the list
// 3-1|5 -> 5 gets removed
AccessExpireLRUCache<int, int> aCache(3, DURSLEEP);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
SharedPtr<int> tmp = aCache.get(1);
assertTrue (!tmp.isNull());
assertTrue (*tmp == 2);
assertTrue (aCache.size() == 1);
Thread::sleep(DURWAIT);
assertTrue (aCache.size() == 0);
assertTrue (!aCache.has(1));
// tmp must still be valid, access it
assertTrue (*tmp == 2);
tmp = aCache.get(1);
assertTrue (!tmp);
aCache.add(1, 2); // 1
Thread::sleep(DURHALFSLEEP);
aCache.add(3, 4); // 3-1
assertTrue (aCache.has(1));
assertTrue (aCache.has(3));
Thread::sleep(DURHALFSLEEP+50); //3|1
assertTrue (!aCache.has(1));
assertTrue (*aCache.get(3) == 4);
Thread::sleep(DURHALFSLEEP+25); //3|1
assertTrue (*aCache.get(3) == 4);
// removing illegal entries should work too
aCache.remove(666);
aCache.clear();
assertTrue (!aCache.has(5));
assertTrue (!aCache.has(3));
}
void ExpireLRUCacheTest::testCacheSize0()
{
// cache size 0 is illegal
try
{
ExpireLRUCache<int, int> aCache(0);
failmsg ("cache size of 0 is illegal, test should fail");
}
catch (Poco::InvalidArgumentException&)
{
}
}
void ExpireLRUCacheTest::testCacheSize1()
{
ExpireLRUCache<int, int> aCache(1);
aCache.add(1, 2);
assertTrue (aCache.has(1));
assertTrue (*aCache.get(1) == 2);
aCache.add(3, 4); // replaces 1
assertTrue (!aCache.has(1));
assertTrue (aCache.has(3));
assertTrue (*aCache.get(3) == 4);
aCache.add(5, 6);
assertTrue (!aCache.has(1));
assertTrue (!aCache.has(3));
assertTrue (aCache.has(5));
assertTrue (*aCache.get(5) == 6);
aCache.remove(5);
assertTrue (!aCache.has(5));
// removing illegal entries should work too
aCache.remove(666);
}
void ExpireLRUCacheTest::testCacheSize2()
{
// 3-1 represents the cache sorted by pos, elements get replaced at the end of the list
// 3-1|5 -> 5 gets removed
ExpireLRUCache<int, int> aCache(2);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
assertTrue (*aCache.get(1) == 2);
aCache.add(3, 4); // 3-1
assertTrue (aCache.has(1));
assertTrue (aCache.has(3));
assertTrue (*aCache.get(1) == 2); // 1-3
assertTrue (*aCache.get(3) == 4); // 3-1
aCache.add(5, 6); // 5-3|1
assertTrue (!aCache.has(1));
assertTrue (aCache.has(3));
assertTrue (aCache.has(5));
assertTrue (*aCache.get(5) == 6); // 5-3
assertTrue (*aCache.get(3) == 4); // 3-5
// test remove from the end and the beginning of the list
aCache.remove(5); // 3
assertTrue (!aCache.has(5));
assertTrue (*aCache.get(3) == 4); // 3
aCache.add(5, 6); // 5-3
assertTrue (*aCache.get(3) == 4); // 3-5
aCache.remove(3); // 5
assertTrue (!aCache.has(3));
assertTrue (*aCache.get(5) == 6); // 5
// removing illegal entries should work too
aCache.remove(666);
aCache.clear();
assertTrue (!aCache.has(5));
}
void ExpireLRUCacheTest::testCacheSizeN()
{
// 3-1 represents the cache sorted by pos, elements get replaced at the end of the list
// 3-1|5 -> 5 gets removed
ExpireLRUCache<int, int> aCache(3);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
assertTrue (*aCache.get(1) == 2);
aCache.add(3, 4); // 3-1
assertTrue (aCache.has(1));
assertTrue (aCache.has(3));
assertTrue (*aCache.get(1) == 2); // 1-3
assertTrue (*aCache.get(3) == 4); // 3-1
aCache.add(5, 6); // 5-3-1
assertTrue (aCache.has(1));
assertTrue (aCache.has(3));
assertTrue (aCache.has(5));
assertTrue (*aCache.get(5) == 6); // 5-3-1
assertTrue (*aCache.get(3) == 4); // 3-5-1
aCache.add(7, 8); // 7-5-3|1
assertTrue (!aCache.has(1));
assertTrue (aCache.has(7));
assertTrue (aCache.has(3));
assertTrue (aCache.has(5));
assertTrue (*aCache.get(5) == 6); // 5-7-3
assertTrue (*aCache.get(3) == 4); // 3-5-7
assertTrue (*aCache.get(7) == 8); // 7-3-5
// test remove from the end and the beginning of the list
aCache.remove(5); // 7-3
assertTrue (!aCache.has(5));
assertTrue (*aCache.get(3) == 4); // 3-7
aCache.add(5, 6); // 5-3-7
assertTrue (*aCache.get(7) == 8); // 7-5-3
aCache.remove(7); // 5-3
assertTrue (!aCache.has(7));
assertTrue (aCache.has(3));
assertTrue (*aCache.get(5) == 6); // 5-3
// removing illegal entries should work too
aCache.remove(666);
aCache.clear();
assertTrue (!aCache.has(5));
assertTrue (!aCache.has(3));
}
void ExpireLRUCacheTest::testDuplicateAdd()
{
ExpireLRUCache<int, int> aCache(3);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
assertTrue (*aCache.get(1) == 2);
aCache.add(1, 3);
assertTrue (aCache.has(1));
assertTrue (*aCache.get(1) == 3);
}
void ExpireLRUCacheTest::testAccessExpireGet()
{
ExpireLRUCache<int, int> aCache(3, DURSLEEP);
aCache.add(1, 2); // 1
assertTrue (aCache.has(1));
SharedPtr<int> tmp = aCache.get(1);
assertTrue (!tmp.isNull());
assertTrue (*tmp == 2);
Thread::sleep(DURWAIT);
tmp = aCache.get(1);
assertTrue (tmp.isNull());
}
void ExpireLRUCacheTest::setUp()
{
}
void ExpireLRUCacheTest::tearDown()
{
}
CppUnit::Test* ExpireLRUCacheTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ExpireLRUCacheTest");
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testClear);
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testExpire0);
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testExpireN);
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testAccessExpireN);
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSize0);
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSize1);
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSize2);
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testCacheSizeN);
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testDuplicateAdd);
CppUnit_addTest(pSuite, ExpireLRUCacheTest, testAccessExpireGet);
return pSuite;
}

View File

@@ -0,0 +1,43 @@
//
// ExpireLRUCacheTest.h
//
// Tests for ExpireLRUCache
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef ExpireLRUCacheTest_INCLUDED
#define ExpireLRUCacheTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class ExpireLRUCacheTest: public CppUnit::TestCase
{
public:
ExpireLRUCacheTest(const std::string& name);
~ExpireLRUCacheTest();
void testClear();
void testExpire0();
void testExpireN();
void testAccessExpireN();
void testCacheSize0();
void testCacheSize1();
void testCacheSize2();
void testCacheSizeN();
void testDuplicateAdd();
void testAccessExpireGet();
void setUp();
void tearDown();
static CppUnit::Test* suite();
};
#endif // ExpireLRUCacheTest_INCLUDED

View File

@@ -0,0 +1,202 @@
//
// FIFOBufferStreamTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "FIFOBufferStreamTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/FIFOBuffer.h"
#include "Poco/FIFOBufferStream.h"
#include "Poco/Delegate.h"
using Poco::FIFOBuffer;
using Poco::FIFOBufferStream;
using Poco::delegate;
FIFOBufferStreamTest::FIFOBufferStreamTest(const std::string& name): CppUnit::TestCase(name)
{
}
FIFOBufferStreamTest::~FIFOBufferStreamTest()
{
}
void FIFOBufferStreamTest::testInput()
{
const char* data = "This is a test";
FIFOBuffer fb1(data, 14);
FIFOBufferStream str1(fb1);
assertTrue (str1.rdbuf()->fifoBuffer().isFull());
int c = str1.get();
assertTrue (c == 'T');
c = str1.get();
assertTrue (c == 'h');
std::string str;
str1 >> str;
assertTrue (str == "is");
char buffer[32];
str1.read(buffer, sizeof(buffer));
assertTrue (str1.gcount() == 10);
buffer[str1.gcount()] = 0;
assertTrue (std::string(" is a test") == buffer);
const char* data2 = "123";
FIFOBufferStream str2(data2, 3);
c = str2.get();
assertTrue (c == '1');
assertTrue (str2.good());
c = str2.get();
assertTrue (c == '2');
str2.unget();
c = str2.get();
assertTrue (c == '2');
assertTrue (str2.good());
c = str2.get();
assertTrue (c == '3');
assertTrue (str2.good());
c = str2.get();
assertTrue (c == -1);
assertTrue (str2.eof());
}
void FIFOBufferStreamTest::testOutput()
{
char output[64];
FIFOBufferStream iostr1(output, 64);
iostr1 << "This is a test " << 42 << std::ends << std::flush;
assertTrue (std::string("This is a test 42") == output);
}
void FIFOBufferStreamTest::testNotify()
{
FIFOBuffer fb(18);
FIFOBufferStream iostr(fb);
assertTrue (iostr.rdbuf()->fifoBuffer().isEmpty());
assertTrue (0 == _readableToNot);
assertTrue (0 == _notToReadable);
assertTrue (0 == _writableToNot);
assertTrue (0 == _notToWritable);
iostr.readable += delegate(this, &FIFOBufferStreamTest::onReadable);
iostr.writable += delegate(this, &FIFOBufferStreamTest::onWritable);
iostr << "This is a test " << 42 << std::ends << std::flush;
assertTrue (iostr.rdbuf()->fifoBuffer().isFull());
assertTrue (0 == _readableToNot);
assertTrue (1 == _notToReadable);
assertTrue (1 == _writableToNot);
assertTrue (0 == _notToWritable);
char input[64];
iostr >> input;
assertTrue (std::string("This") == input);
assertTrue (iostr.rdbuf()->fifoBuffer().isEmpty());
assertTrue (1 == _readableToNot);
assertTrue (1 == _notToReadable);
assertTrue (1 == _writableToNot);
assertTrue (1 == _notToWritable);
iostr >> input;
assertTrue (std::string("is") == input);
assertTrue (1 == _readableToNot);
assertTrue (1 == _notToReadable);
assertTrue (1 == _writableToNot);
assertTrue (1 == _notToWritable);
iostr >> input;
assertTrue (std::string("a") == input);
assertTrue (1 == _readableToNot);
assertTrue (1 == _notToReadable);
assertTrue (1 == _writableToNot);
assertTrue (1 == _notToWritable);
iostr >> input;
assertTrue (std::string("test") == input);
assertTrue (1 == _readableToNot);
assertTrue (1 == _notToReadable);
assertTrue (1 == _writableToNot);
assertTrue (1 == _notToWritable);
iostr >> input;
assertTrue (std::string("42") == input);
assertTrue (1 == _readableToNot);
assertTrue (1 == _notToReadable);
assertTrue (1 == _writableToNot);
assertTrue (1 == _notToWritable);
iostr.clear();
assertTrue (iostr.good());
iostr << "This is a test " << 42 << std::ends << std::flush;
assertTrue (iostr.rdbuf()->fifoBuffer().isFull());
assertTrue (1 == _readableToNot);
assertTrue (2 == _notToReadable);
assertTrue (2 == _writableToNot);
assertTrue (1 == _notToWritable);
iostr.readable -= delegate(this, &FIFOBufferStreamTest::onReadable);
iostr.writable -= delegate(this, &FIFOBufferStreamTest::onWritable);
}
void FIFOBufferStreamTest::onReadable(bool& b)
{
if (b) ++_notToReadable;
else ++_readableToNot;
};
void FIFOBufferStreamTest::onWritable(bool& b)
{
if (b) ++_notToWritable;
else ++_writableToNot;
}
void FIFOBufferStreamTest::setUp()
{
_readableToNot = 0;
_notToReadable = 0;
_writableToNot = 0;
_notToWritable = 0;
}
void FIFOBufferStreamTest::tearDown()
{
}
CppUnit::Test* FIFOBufferStreamTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FIFOBufferStreamTest");
CppUnit_addTest(pSuite, FIFOBufferStreamTest, testInput);
CppUnit_addTest(pSuite, FIFOBufferStreamTest, testOutput);
CppUnit_addTest(pSuite, FIFOBufferStreamTest, testNotify);
return pSuite;
}

View File

@@ -0,0 +1,48 @@
//
// FIFOBufferStreamTest.h
//
// Definition of the FIFOBufferStreamTest class.
//
// Copyright (c) 2009, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef FIFOBufferStreamTest_INCLUDED
#define FIFOBufferStreamTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class FIFOBufferStreamTest: public CppUnit::TestCase
{
public:
FIFOBufferStreamTest(const std::string& name);
~FIFOBufferStreamTest();
void testInput();
void testOutput();
void testNotify();
void setUp();
void tearDown();
static CppUnit::Test* suite();
protected:
void onReadable(bool& b);
void onWritable(bool& b);
private:
int _readableToNot;
int _notToReadable;
int _writableToNot;
int _notToWritable;
};
#endif // FIFOBufferStreamTest_INCLUDED

View File

@@ -0,0 +1,435 @@
//
// FIFOEventTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "FIFOEventTest.h"
#include "DummyDelegate.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Delegate.h"
#include "Poco/Expire.h"
#include "Poco/Thread.h"
#include "Poco/Exception.h"
using namespace Poco;
#define LARGEINC 100
FIFOEventTest::FIFOEventTest(const std::string& name): CppUnit::TestCase(name)
{
}
FIFOEventTest::~FIFOEventTest()
{
}
void FIFOEventTest::testNoDelegate()
{
int tmp = 0;
EventArgs args;
assertTrue (_count == 0);
Void.notify(this);
assertTrue (_count == 0);
Void += delegate(this, &FIFOEventTest::onVoid);
Void -= delegate(this, &FIFOEventTest::onVoid);
Void.notify(this);
assertTrue (_count == 0);
Simple.notify(this, tmp);
assertTrue (_count == 0);
Simple += delegate(this, &FIFOEventTest::onSimple);
Simple -= delegate(this, &FIFOEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 0);
ConstSimple += delegate(this, &FIFOEventTest::onConstSimple);
ConstSimple -= delegate(this, &FIFOEventTest::onConstSimple);
ConstSimple.notify(this, tmp);
assertTrue (_count == 0);
//Note: passing &args will not work due to &
EventArgs* pArgs = &args;
Complex += delegate(this, &FIFOEventTest::onComplex);
Complex -= delegate(this, &FIFOEventTest::onComplex);
Complex.notify(this, pArgs);
assertTrue (_count == 0);
Complex2 += delegate(this, &FIFOEventTest::onComplex2);
Complex2 -= delegate(this, &FIFOEventTest::onComplex2);
Complex2.notify(this, args);
assertTrue (_count == 0);
const EventArgs* pCArgs = &args;
ConstComplex += delegate(this, &FIFOEventTest::onConstComplex);
ConstComplex -= delegate(this, &FIFOEventTest::onConstComplex);
ConstComplex.notify(this, pCArgs);
assertTrue (_count == 0);
Const2Complex += delegate(this, &FIFOEventTest::onConst2Complex);
Const2Complex -= delegate(this, &FIFOEventTest::onConst2Complex);
Const2Complex.notify(this, pArgs);
assertTrue (_count == 0);
}
void FIFOEventTest::testSingleDelegate()
{
int tmp = 0;
EventArgs args;
assertTrue (_count == 0);
Void += delegate(this, &FIFOEventTest::onVoid);
Void.notify(this);
assertTrue (_count == 1);
Simple += delegate(this, &FIFOEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 2);
ConstSimple += delegate(this, &FIFOEventTest::onConstSimple);
ConstSimple.notify(this, tmp);
assertTrue (_count == 3);
EventArgs* pArgs = &args;
Complex += delegate(this, &FIFOEventTest::onComplex);
Complex.notify(this, pArgs);
assertTrue (_count == 4);
Complex2 += delegate(this, &FIFOEventTest::onComplex2);
Complex2.notify(this, args);
assertTrue (_count == 5);
const EventArgs* pCArgs = &args;
ConstComplex += delegate(this, &FIFOEventTest::onConstComplex);
ConstComplex.notify(this, pCArgs);
assertTrue (_count == 6);
Const2Complex += delegate(this, &FIFOEventTest::onConst2Complex);
Const2Complex.notify(this, pArgs);
assertTrue (_count == 7);
// check if 2nd notify also works
Const2Complex.notify(this, pArgs);
assertTrue (_count == 8);
}
void FIFOEventTest::testDuplicateRegister()
{
int tmp = 0;
assertTrue (_count == 0);
Simple += delegate(this, &FIFOEventTest::onSimple);
Simple += delegate(this, &FIFOEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 2);
Simple -= delegate(this, &FIFOEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 3);
}
void FIFOEventTest::testDuplicateUnregister()
{
// duplicate unregister shouldn't give an error,
int tmp = 0;
assertTrue (_count == 0);
Simple -= delegate(this, &FIFOEventTest::onSimple); // should work
Simple.notify(this, tmp);
assertTrue (_count == 0);
Simple += delegate(this, &FIFOEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 1);
Simple -= delegate(this, &FIFOEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 1);
Simple -= delegate(this, &FIFOEventTest::onSimple);
Simple.notify(this, tmp);
assertTrue (_count == 1);
}
void FIFOEventTest::testDisabling()
{
int tmp = 0;
assertTrue (_count == 0);
Simple += delegate(this, &FIFOEventTest::onSimple);
Simple.disable();
Simple.notify(this, tmp);
assertTrue (_count == 0);
Simple.enable();
Simple.notify(this, tmp);
assertTrue (_count == 1);
// unregister should also work with disabled event
Simple.disable();
Simple -= delegate(this, &FIFOEventTest::onSimple);
Simple.enable();
Simple.notify(this, tmp);
assertTrue (_count == 1);
}
void FIFOEventTest::testFIFOOrder()
{
DummyDelegate o1;
DummyDelegate o2;
assertTrue (_count == 0);
Simple += delegate(&o1, &DummyDelegate::onSimple);
Simple += delegate(&o2, &DummyDelegate::onSimple2);
int tmp = 0;
Simple.notify(this, tmp);
assertTrue (tmp == 2);
Simple -= delegate(&o1, &DummyDelegate::onSimple);
Simple -= delegate(&o2, &DummyDelegate::onSimple2);
// now try with the wrong order
Simple += delegate(&o2, &DummyDelegate::onSimple2);
Simple += delegate(&o1, &DummyDelegate::onSimple);
try
{
tmp = 0;
Simple.notify(this, tmp);
failmsg ("Notify should not work");
}
catch (Poco::InvalidArgumentException&)
{
}
}
void FIFOEventTest::testFIFOOrderExpire()
{
// expire must not break order!
DummyDelegate o1;
DummyDelegate o2;
assertTrue (_count == 0);
Simple += delegate(&o1, &DummyDelegate::onSimple, 5000);
Simple += delegate(&o2, &DummyDelegate::onSimple2, 5000);
int tmp = 0;
Simple.notify(this, tmp);
assertTrue (tmp == 2);
// both ways of unregistering should work
Simple -= delegate(&o1, &DummyDelegate::onSimple, 6000);
Simple -= delegate(&o2, &DummyDelegate::onSimple2);
Simple.notify(this, tmp);
assertTrue (tmp == 2);
// now start mixing of expire and non expire
tmp = 0;
Simple += delegate(&o1, &DummyDelegate::onSimple);
Simple += delegate(&o2, &DummyDelegate::onSimple2, 5000);
Simple.notify(this, tmp);
assertTrue (tmp == 2);
Simple -= delegate(&o2, &DummyDelegate::onSimple2);
// it is not forbidden to unregister a non expiring event with an expire decorator (it is just stupid ;-))
Simple -= delegate(&o1, &DummyDelegate::onSimple, 6000);
Simple.notify(this, tmp);
assertTrue (tmp == 2);
// now try with the wrong order
Simple += delegate(&o2, &DummyDelegate::onSimple2, 5000);
Simple += delegate(&o1, &DummyDelegate::onSimple);
try
{
tmp = 0;
Simple.notify(this, tmp);
failmsg ("Notify should not work");
}
catch (Poco::InvalidArgumentException&)
{
}
}
void FIFOEventTest::testExpire()
{
int tmp = 0;
assertTrue (_count == 0);
Simple += delegate(this, &FIFOEventTest::onSimple, 500);
Simple.notify(this, tmp);
assertTrue (_count == 1);
Poco::Thread::sleep(700);
Simple.notify(this, tmp);
assertTrue (_count == 1);
}
void FIFOEventTest::testExpireReRegister()
{
int tmp = 0;
assertTrue (_count == 0);
Simple += delegate(this, &FIFOEventTest::onSimple, 500);
Simple.notify(this, tmp);
assertTrue (_count == 1);
Poco::Thread::sleep(200);
Simple.notify(this, tmp);
assertTrue (_count == 2);
// renew registration
Simple += delegate(this, &FIFOEventTest::onSimple, 600);
Poco::Thread::sleep(400);
Simple.notify(this, tmp);
assertTrue (_count == 3);
Poco::Thread::sleep(300);
Simple.notify(this, tmp);
assertTrue (_count == 3);
}
void FIFOEventTest::testReturnParams()
{
DummyDelegate o1;
Simple += delegate(&o1, &DummyDelegate::onSimple);
int tmp = 0;
Simple.notify(this, tmp);
assertTrue (tmp == 1);
}
void FIFOEventTest::testOverwriteDelegate()
{
DummyDelegate o1;
Simple += delegate(&o1, &DummyDelegate::onSimple);
Simple += delegate(&o1, &DummyDelegate::onSimple2);
int tmp = 0; // onsimple requires 0 as input
Simple.notify(this, tmp);
assertTrue (tmp == 2);
}
void FIFOEventTest::testAsyncNotify()
{
Poco::FIFOEvent<int >* pSimple= new Poco::FIFOEvent<int>();
(*pSimple) += delegate(this, &FIFOEventTest::onAsync);
assertTrue (_count == 0);
int tmp = 0;
Poco::ActiveResult<int>retArg = pSimple->notifyAsync(this, tmp);
delete pSimple; // must work even when the event got deleted!
pSimple = NULL;
assertTrue (_count == 0);
retArg.wait();
assertTrue (retArg.data() == tmp);
assertTrue (_count == LARGEINC);
}
void FIFOEventTest::onVoid(const void* pSender)
{
_count++;
}
void FIFOEventTest::onSimple(const void* pSender, int& i)
{
_count++;
}
void FIFOEventTest::onSimpleOther(const void* pSender, int& i)
{
_count+=100;
}
void FIFOEventTest::onConstSimple(const void* pSender, const int& i)
{
_count++;
}
void FIFOEventTest::onComplex(const void* pSender, Poco::EventArgs* & i)
{
_count++;
}
void FIFOEventTest::onComplex2(const void* pSender, Poco::EventArgs & i)
{
_count++;
}
void FIFOEventTest::onConstComplex(const void* pSender, const Poco::EventArgs*& i)
{
_count++;
}
void FIFOEventTest::onConst2Complex(const void* pSender, const Poco::EventArgs * const & i)
{
_count++;
}
void FIFOEventTest::onAsync(const void* pSender, int& i)
{
Poco::Thread::sleep(700);
_count += LARGEINC ;
}
int FIFOEventTest::getCount() const
{
return _count;
}
void FIFOEventTest::setUp()
{
_count = 0;
// must clear events, otherwise repeating test executions will fail
// because tests are only created once, only setup is called before
// each test run
Void.clear();
Simple.clear();
ConstSimple.clear();
Complex.clear();
Complex2.clear();
ConstComplex.clear();
Const2Complex.clear();
}
void FIFOEventTest::tearDown()
{
}
CppUnit::Test* FIFOEventTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FIFOEventTest");
CppUnit_addTest(pSuite, FIFOEventTest, testNoDelegate);
CppUnit_addTest(pSuite, FIFOEventTest, testSingleDelegate);
CppUnit_addTest(pSuite, FIFOEventTest, testReturnParams);
CppUnit_addTest(pSuite, FIFOEventTest, testDuplicateRegister);
CppUnit_addTest(pSuite, FIFOEventTest, testDuplicateUnregister);
CppUnit_addTest(pSuite, FIFOEventTest, testDisabling);
CppUnit_addTest(pSuite, FIFOEventTest, testFIFOOrder);
CppUnit_addTest(pSuite, FIFOEventTest, testFIFOOrderExpire);
CppUnit_addTest(pSuite, FIFOEventTest, testExpire);
CppUnit_addTest(pSuite, FIFOEventTest, testExpireReRegister);
CppUnit_addTest(pSuite, FIFOEventTest, testOverwriteDelegate);
CppUnit_addTest(pSuite, FIFOEventTest, testAsyncNotify);
return pSuite;
}

View File

@@ -0,0 +1,70 @@
//
// FIFOEventTest.h
//
// Definition of the FIFOEventTest class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef FIFOEventTest_INCLUDED
#define FIFOEventTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
#include "Poco/FIFOEvent.h"
#include "Poco/EventArgs.h"
class FIFOEventTest: public CppUnit::TestCase
{
Poco::FIFOEvent<void> Void;
Poco::FIFOEvent<int> Simple;
Poco::FIFOEvent<const int> ConstSimple;
Poco::FIFOEvent<Poco::EventArgs*> Complex;
Poco::FIFOEvent<Poco::EventArgs> Complex2;
Poco::FIFOEvent<const Poco::EventArgs*> ConstComplex;
Poco::FIFOEvent<const Poco::EventArgs * const> Const2Complex;
public:
FIFOEventTest(const std::string& name);
~FIFOEventTest();
void testNoDelegate();
void testSingleDelegate();
void testDuplicateRegister();
void testDuplicateUnregister();
void testDisabling();
void testFIFOOrder();
void testFIFOOrderExpire();
void testExpire();
void testExpireReRegister();
void testReturnParams();
void testOverwriteDelegate();
void testAsyncNotify();
void setUp();
void tearDown();
static CppUnit::Test* suite();
protected:
void onVoid(const void* pSender);
void onSimple(const void* pSender, int& i);
void onSimpleOther(const void* pSender, int& i);
void onConstSimple(const void* pSender, const int& i);
void onComplex(const void* pSender, Poco::EventArgs* & i);
void onComplex2(const void* pSender, Poco::EventArgs & i);
void onConstComplex(const void* pSender, const Poco::EventArgs*& i);
void onConst2Complex(const void* pSender, const Poco::EventArgs * const & i);
void onAsync(const void* pSender, int& i);
int getCount() const;
private:
int _count;
};
#endif // FIFOEventTest_INCLUDED

View File

@@ -0,0 +1,156 @@
//
// FPETest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "FPETest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/FPEnvironment.h"
using Poco::FPE;
FPETest::FPETest(const std::string& name): CppUnit::TestCase(name)
{
}
FPETest::~FPETest()
{
}
void FPETest::testClassify()
{
{
float a = 0.0f;
float b = 0.0f;
float nan = a/b;
float inf = 1.0f/b;
assertTrue (FPE::isNaN(nan));
assertTrue (!FPE::isNaN(a));
assertTrue (FPE::isInfinite(inf));
assertTrue (!FPE::isInfinite(a));
}
{
double a = 0;
double b = 0;
double nan = a/b;
double inf = 1.0/b;
assertTrue (FPE::isNaN(nan));
assertTrue (!FPE::isNaN(a));
assertTrue (FPE::isInfinite(inf));
assertTrue (!FPE::isInfinite(a));
}
}
#if defined(__HP_aCC)
#pragma OPTIMIZE OFF
#elif defined(_MSC_VER)
#pragma optimize("", off)
#elif defined(__APPLE__) && defined(POCO_COMPILER_GCC)
#pragma GCC optimization_level 0
#endif
double mult(double a, double b)
{
return a*b;
}
double div(double a, double b)
{
return a/b;
}
void FPETest::testFlags()
{
FPE::clearFlags();
// some compilers are intelligent enough to optimize the calculations below away.
// unfortunately this leads to a failing test, so we have to trick out the
// compiler's optimizer a little bit by doing something with the results.
volatile double a = 10;
volatile double b = 0;
volatile double c = div(a, b);
#if !defined(POCO_NO_FPENVIRONMENT)
assertTrue (FPE::isFlag(FPE::FP_DIVIDE_BY_ZERO));
#endif
assertTrue (FPE::isInfinite(c));
FPE::clearFlags();
a = 1.23456789e210;
b = 9.87654321e210;
c = mult(a, b);
#if !defined(POCO_NO_FPENVIRONMENT)
assertTrue (FPE::isFlag(FPE::FP_OVERFLOW));
#endif
assertEqualDelta(c, c, 0);
FPE::clearFlags();
a = 1.23456789e-99;
b = 9.87654321e210;
c = div(a, b);
#if !defined(POCO_NO_FPENVIRONMENT)
assertTrue (FPE::isFlag(FPE::FP_UNDERFLOW));
#endif
assertEqualDelta(c, c, 0);
}
#if defined(__HP_aCC)
#pragma OPTIMIZE ON
#elif defined(_MSC_VER)
#pragma optimize("", on)
#elif defined(__APPLE__) && defined(POCO_COMPILER_GCC)
#pragma GCC optimization_level reset
#endif
void FPETest::testRound()
{
#if !defined(__osf__) && !defined(__VMS) && !defined(POCO_NO_FPENVIRONMENT)
FPE::setRoundingMode(FPE::FP_ROUND_TONEAREST);
assertTrue (FPE::getRoundingMode() == FPE::FP_ROUND_TONEAREST);
{
FPE env(FPE::FP_ROUND_TOWARDZERO);
assertTrue (FPE::getRoundingMode() == FPE::FP_ROUND_TOWARDZERO);
}
assertTrue (FPE::getRoundingMode() == FPE::FP_ROUND_TONEAREST);
#endif
}
void FPETest::setUp()
{
}
void FPETest::tearDown()
{
}
CppUnit::Test* FPETest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FPETest");
CppUnit_addTest(pSuite, FPETest, testClassify);
CppUnit_addTest(pSuite, FPETest, testFlags);
CppUnit_addTest(pSuite, FPETest, testRound);
return pSuite;
}

View File

@@ -0,0 +1,40 @@
//
// FPETest.h
//
// Definition of the FPETest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef FPETest_INCLUDED
#define FPETest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class FPETest: public CppUnit::TestCase
{
public:
FPETest(const std::string& name);
~FPETest();
void testClassify();
void testFlags();
void testRound();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // FPETest_INCLUDED

View File

@@ -0,0 +1,652 @@
//
// FileChannelTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "FileChannelTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/FileChannel.h"
#include "Poco/Message.h"
#include "Poco/AutoPtr.h"
#include "Poco/TemporaryFile.h"
#include "Poco/Thread.h"
#include "Poco/File.h"
#include "Poco/Path.h"
#include "Poco/Timestamp.h"
#include "Poco/DateTime.h"
#include "Poco/LocalDateTime.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/NumberFormatter.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/Exception.h"
#include <vector>
using Poco::FileChannel;
using Poco::Message;
using Poco::AutoPtr;
using Poco::TemporaryFile;
using Poco::Thread;
using Poco::File;
using Poco::Path;
using Poco::Timestamp;
using Poco::NumberFormatter;
using Poco::DateTime;
using Poco::LocalDateTime;
using Poco::DateTimeFormatter;
using Poco::DateTimeFormat;
using Poco::DirectoryIterator;
using Poco::InvalidArgumentException;
FileChannelTest::FileChannelTest(const std::string& name): CppUnit::TestCase(name)
{
}
FileChannelTest::~FileChannelTest()
{
}
void FileChannelTest::testRotateBySize()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_ROTATION, "2 K");
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
for (int i = 0; i < 200; ++i)
{
pChannel->log(msg);
}
File f(name + ".0");
assertTrue (f.exists());
f = name + ".1";
assertTrue (f.exists());
f = name + ".2";
assertTrue (!f.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testRotateByAge()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_ROTATION, "2 seconds");
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
for (int i = 0; i < 15; ++i)
{
pChannel->log(msg);
Thread::sleep(300);
}
File f(name + ".0");
assertTrue (f.exists());
f = name + ".1";
assertTrue (f.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testRotateAtTimeDayUTC()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_TIMES, "utc");
pChannel->setProperty(FileChannel::PROP_ROTATION, rotation<DateTime>(DAY_HOUR_MIN));
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
int min = DateTime().minute();
while (DateTime().minute() == min)
{
pChannel->log(msg);
Thread::sleep(1000);
}
pChannel->log(msg);
File f(name + ".0");
assertTrue (f.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testRotateAtTimeDayLocal()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_TIMES, "local");
pChannel->setProperty(FileChannel::PROP_ROTATION, rotation<LocalDateTime>(DAY_HOUR_MIN));
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
int min = DateTime().minute();
while (DateTime().minute() == min)
{
pChannel->log(msg);
Thread::sleep(1000);
}
pChannel->log(msg);
File f(name + ".0");
assertTrue (f.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testRotateAtTimeHourUTC()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_TIMES, "utc");
pChannel->setProperty(FileChannel::PROP_ROTATION, rotation<DateTime>(HOUR_MIN));
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
int min = DateTime().minute();
while (DateTime().minute() == min)
{
pChannel->log(msg);
Thread::sleep(1000);
}
pChannel->log(msg);
File f(name + ".0");
assertTrue (f.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testRotateAtTimeHourLocal()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_TIMES, "local");
pChannel->setProperty(FileChannel::PROP_ROTATION, rotation<LocalDateTime>(HOUR_MIN));
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
int min = DateTime().minute();
while (DateTime().minute() == min)
{
pChannel->log(msg);
Thread::sleep(1000);
}
pChannel->log(msg);
File f(name + ".0");
assertTrue (f.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testRotateAtTimeMinUTC()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_TIMES, "utc");
pChannel->setProperty(FileChannel::PROP_ROTATION, rotation<DateTime>(MIN));
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
int min = DateTime().minute();
while (DateTime().minute() == min)
{
pChannel->log(msg);
Thread::sleep(1000);
}
pChannel->log(msg);
File f(name + ".0");
assertTrue (f.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testRotateAtTimeMinLocal()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_TIMES, "local");
pChannel->setProperty(FileChannel::PROP_ROTATION, rotation<LocalDateTime>(MIN));
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
int min = DateTime().minute();
while (DateTime().minute() == min)
{
pChannel->log(msg);
Thread::sleep(1000);
}
pChannel->log(msg);
File f(name + ".0");
assertTrue (f.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testArchive()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_ROTATION, "2 K");
pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number");
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
for (int i = 0; i < 200; ++i)
{
pChannel->log(msg);
}
File f(name + ".0");
assertTrue (f.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testCompress()
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K");
pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number");
pChannel->setProperty(FileChannel::PROP_COMPRESS, "true");
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
for (int i = 0; i < 200; ++i)
{
pChannel->log(msg);
}
Thread::sleep(3000); // allow time for background compression
File f0(name + ".0.gz");
assertTrue (f0.exists());
File f1(name + ".1.gz");
assertTrue (f1.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::purgeAge(const std::string& pa)
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K");
pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number");
pChannel->setProperty(FileChannel::PROP_PURGEAGE, pa);
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
for (int i = 0; i < 200; ++i)
{
pChannel->log(msg);
}
File f0(name + ".0");
assertTrue (f0.exists());
File f1(name + ".1");
assertTrue (f1.exists());
File f2(name + ".2");
assertTrue (f2.exists());
Thread::sleep(5000);
for (int i = 0; i < 50; ++i)
{
pChannel->log(msg);
}
assertTrue (!f2.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::noPurgeAge(const std::string& npa)
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K");
pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number");
pChannel->setProperty(FileChannel::PROP_PURGEAGE, npa);
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
for (int i = 0; i < 200; ++i)
{
pChannel->log(msg);
}
File f0(name + ".0");
assertTrue (f0.exists());
File f1(name + ".1");
assertTrue (f1.exists());
File f2(name + ".2");
assertTrue (f2.exists());
Thread::sleep(5000);
for (int i = 0; i < 50; ++i)
{
pChannel->log(msg);
}
assertTrue (f2.exists());
}
catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testPurgeAge()
{
purgeAge("5 seconds");
try
{
noPurgeAge("0 seconds");
fail ("must fail");
} catch (InvalidArgumentException&)
{
}
noPurgeAge("");
noPurgeAge("none");
}
void FileChannelTest::purgeCount(const std::string& pc)
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K");
pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number");
pChannel->setProperty(FileChannel::PROP_PURGECOUNT, pc);
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
for (int i = 0; i < 200; ++i)
{
pChannel->log(msg);
Thread::sleep(50);
}
File f0(name + ".0");
assertTrue (f0.exists());
File f1(name + ".1");
assertTrue (f1.exists());
File f2(name + ".2");
assertTrue (!f2.exists());
} catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::noPurgeCount(const std::string& npc)
{
std::string name = filename();
try
{
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_ROTATION, "1 K");
pChannel->setProperty(FileChannel::PROP_ARCHIVE, "number");
pChannel->setProperty(FileChannel::PROP_PURGECOUNT, npc);
pChannel->open();
Message msg("source", "This is a log file entry", Message::PRIO_INFORMATION);
for (int i = 0; i < 200; ++i)
{
pChannel->log(msg);
Thread::sleep(50);
}
File f0(name + ".0");
assertTrue (f0.exists());
File f1(name + ".1");
assertTrue (f1.exists());
File f2(name + ".2");
assertTrue (f2.exists());
} catch (...)
{
remove(name);
throw;
}
remove(name);
}
void FileChannelTest::testPurgeCount()
{
purgeCount("2");
try
{
noPurgeCount("0");
fail("must fail");
} catch (InvalidArgumentException&)
{
}
noPurgeCount("");
noPurgeCount("none");
}
void FileChannelTest::testWrongPurgeOption()
{
std::string name = filename();
AutoPtr<FileChannel> pChannel = new FileChannel(name);
pChannel->setProperty(FileChannel::PROP_PURGEAGE, "5 seconds");
try
{
pChannel->setProperty(FileChannel::PROP_PURGEAGE, "peace");
fail("must fail");
} catch (InvalidArgumentException)
{
assertTrue (pChannel->getProperty(FileChannel::PROP_PURGEAGE) == "5 seconds");
}
try
{
pChannel->setProperty(FileChannel::PROP_PURGECOUNT, "peace");
fail("must fail");
} catch (InvalidArgumentException)
{
assertTrue (pChannel->getProperty(FileChannel::PROP_PURGEAGE) == "5 seconds");
}
remove(name);
}
void FileChannelTest::setUp()
{
}
void FileChannelTest::tearDown()
{
}
void FileChannelTest::remove(const std::string& baseName)
{
DirectoryIterator it(Path::current());
DirectoryIterator end;
std::vector<std::string> files;
while (it != end)
{
if (it.name().find(baseName) == 0)
{
files.push_back(it.name());
}
++it;
}
for (std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it)
{
try
{
File f(*it);
f.remove();
} catch (...)
{
}
}
}
std::string FileChannelTest::filename() const
{
std::string name = "log_";
name.append(DateTimeFormatter::format(Timestamp(), "%Y%m%d%H%M%S"));
name.append(".log");
return name;
}
template <class DT>
std::string FileChannelTest::rotation(TimeRotation rtype) const
{
DT now;
std::string rotation;
int day = now.dayOfWeek();
int min = now.minute();
int hour = now.hour();
if (++min == 60)
{
++hour;
min = 0;
}
if (hour == 24)
{
hour = 0;
++day;
day %= 7;
}
switch (rtype)
{
case DAY_HOUR_MIN: // day,hh:m,
rotation = DateTimeFormat::WEEKDAY_NAMES[day];
rotation += ',' + NumberFormatter::format0(hour, 2) + ':' + NumberFormatter::format0(min, 2);
break;
case HOUR_MIN: // hh:mm
rotation = NumberFormatter::format0(hour, 2) + ':' + NumberFormatter::format0(min, 2);
break;
case MIN: // mm
rotation = ':' + NumberFormatter::format0(min, 2);
break;
default:
rotation = "";
break;
}
return rotation;
}
CppUnit::Test* FileChannelTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FileChannelTest");
CppUnit_addTest(pSuite, FileChannelTest, testRotateBySize);
CppUnit_addTest(pSuite, FileChannelTest, testRotateByAge);
CppUnit_addLongTest(pSuite, FileChannelTest, testRotateAtTimeDayUTC);
CppUnit_addLongTest(pSuite, FileChannelTest, testRotateAtTimeDayLocal);
CppUnit_addLongTest(pSuite, FileChannelTest, testRotateAtTimeHourUTC);
CppUnit_addLongTest(pSuite, FileChannelTest, testRotateAtTimeHourLocal);
CppUnit_addLongTest(pSuite, FileChannelTest, testRotateAtTimeMinUTC);
CppUnit_addLongTest(pSuite, FileChannelTest, testRotateAtTimeMinLocal);
CppUnit_addTest(pSuite, FileChannelTest, testArchive);
CppUnit_addTest(pSuite, FileChannelTest, testCompress);
CppUnit_addLongTest(pSuite, FileChannelTest, testPurgeAge);
CppUnit_addTest(pSuite, FileChannelTest, testPurgeCount);
CppUnit_addTest(pSuite, FileChannelTest, testWrongPurgeOption);
return pSuite;
}

View File

@@ -0,0 +1,65 @@
//
// FileChannelTest.h
//
// Definition of the FileChannelTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef FileChannelTest_INCLUDED
#define FileChannelTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class FileChannelTest: public CppUnit::TestCase
{
public:
enum TimeRotation
{
DAY_HOUR_MIN = 0,
HOUR_MIN,
MIN
};
FileChannelTest(const std::string& name);
~FileChannelTest();
void testRotateBySize();
void testRotateByAge();
void testRotateAtTimeDayUTC();
void testRotateAtTimeDayLocal();
void testRotateAtTimeHourUTC();
void testRotateAtTimeHourLocal();
void testRotateAtTimeMinUTC();
void testRotateAtTimeMinLocal();
void testArchive();
void testCompress();
void testPurgeAge();
void testPurgeCount();
void testWrongPurgeOption();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
template <class D> std::string rotation(TimeRotation rtype) const;
void remove(const std::string& baseName);
std::string filename() const;
void purgeAge(const std::string& purgeAge);
void noPurgeAge(const std::string& purgeAge);
void purgeCount(const std::string& pc);
void noPurgeCount(const std::string& pc);
};
#endif // FileChannelTest_INCLUDED

View File

@@ -0,0 +1,319 @@
//
// FileStreamTest.cpp
//
// Copyright (c) 2007, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "FileStreamTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/FileStream.h"
#include "Poco/File.h"
#include "Poco/TemporaryFile.h"
#include "Poco/Exception.h"
FileStreamTest::FileStreamTest(const std::string& name): CppUnit::TestCase(name)
{
}
FileStreamTest::~FileStreamTest()
{
}
void FileStreamTest::testRead()
{
#if defined(POCO_OS_FAMILY_WINDOWS)
char tmp[]={'\xc3', '\x84', '\xc3', '\x96', '\xc3', '\x9c', '\xc3', '\xa4', '\xc3', '\xb6', '\xc3', '\xbc', '\0'};
std::string file(tmp);
file.append(".txt");
#else
std::string file("testfile.txt");
#endif
Poco::TemporaryFile::registerForDeletion(file);
Poco::FileOutputStream fos(file, std::ios::binary);
fos << "sometestdata";
fos.close();
Poco::FileInputStream fis(file);
assertTrue (fis.good());
std::string read;
fis >> read;
assertTrue (!read.empty());
}
void FileStreamTest::testWrite()
{
#if defined(POCO_OS_FAMILY_WINDOWS)
char tmp[]={'\xc3', '\x9f', '\xc3', '\x84', '\xc3', '\x96', '\xc3', '\x9c', '\xc3', '\xa4', '\xc3', '\xb6', '\xc3', '\xbc', '\0'};
std::string file(tmp);
file = "dummy_" + file + ".txt";
#else
std::string file("dummy_file.txt");
#endif
Poco::TemporaryFile::registerForDeletion(file);
Poco::FileOutputStream fos(file);
assertTrue (fos.good());
fos << "hiho";
fos.close();
Poco::FileInputStream fis(file);
assertTrue (fis.good());
std::string read;
fis >> read;
assertTrue (read == "hiho");
}
void FileStreamTest::testReadWrite()
{
char tmp[]={'\xc3', '\x9f', '\xc3', '\x84', '\xc3', '\x96', '\xc3', '\x9c', '\xc3', '\xa4', '\xc3', '\xb6', '\xc3', '\xbc', '\0'};
std::string file(tmp);
file = "dummy_" + file + ".txt";
Poco::TemporaryFile::registerForDeletion(file);
Poco::FileStream fos(file);
assertTrue (fos.good());
fos << "hiho";
fos.seekg(0, std::ios::beg);
std::string read;
fos >> read;
assertTrue (read == "hiho");
}
void FileStreamTest::testOpen()
{
Poco::FileOutputStream ostr;
ostr.open("test.txt", std::ios::out);
assertTrue (ostr.good());
ostr.close();
}
void FileStreamTest::testOpenModeIn()
{
Poco::File f("nonexistent.txt");
if (f.exists())
f.remove();
try
{
Poco::FileInputStream istr("nonexistent.txt");
fail("nonexistent file - must throw");
}
catch (Poco::Exception&)
{
}
f.createFile();
Poco::FileInputStream istr("nonexistent.txt");
assertTrue (istr.good());
}
void FileStreamTest::testOpenModeOut()
{
Poco::File f("test.txt");
if (f.exists())
f.remove();
Poco::FileOutputStream ostr1("test.txt");
ostr1 << "Hello, world!";
ostr1.close();
assertTrue (f.exists());
assertTrue (f.getSize() != 0);
Poco::FileStream str1("test.txt");
str1.close();
assertTrue (f.exists());
assertTrue (f.getSize() != 0);
Poco::FileOutputStream ostr2("test.txt");
ostr2.close();
assertTrue (f.exists());
assertTrue (f.getSize() == 0);
f.remove();
}
void FileStreamTest::testOpenModeTrunc()
{
Poco::File f("test.txt");
if (f.exists())
f.remove();
Poco::FileOutputStream ostr1("test.txt");
ostr1 << "Hello, world!";
ostr1.close();
assertTrue (f.exists());
assertTrue (f.getSize() != 0);
Poco::FileStream str1("test.txt", std::ios::trunc);
str1.close();
assertTrue (f.exists());
assertTrue (f.getSize() == 0);
f.remove();
}
void FileStreamTest::testOpenModeAte()
{
Poco::FileOutputStream ostr("test.txt");
ostr << "0123456789";
ostr.close();
Poco::FileStream str1("test.txt", std::ios::ate);
int c = str1.get();
assertTrue (str1.eof());
str1.clear();
str1.seekg(0);
c = str1.get();
assertTrue (c == '0');
str1.close();
Poco::FileStream str2("test.txt", std::ios::ate);
str2 << "abcdef";
str2.seekg(0);
std::string s;
str2 >> s;
assertTrue (s == "0123456789abcdef");
str2.close();
}
void FileStreamTest::testOpenModeApp()
{
Poco::FileOutputStream ostr("test.txt");
ostr << "0123456789";
ostr.close();
Poco::FileStream str1("test.txt", std::ios::app);
str1 << "abc";
str1.seekp(0);
str1 << "def";
str1.close();
Poco::FileInputStream istr("test.txt");
std::string s;
istr >> s;
assertTrue (s == "0123456789abcdef");
istr.close();
}
void FileStreamTest::testSeek()
{
Poco::FileStream str("test.txt", std::ios::trunc);
str << "0123456789abcdef";
str.seekg(0);
int c = str.get();
assertTrue (c == '0');
str.seekg(10);
assertTrue (str.tellg() == std::streampos(10));
c = str.get();
assertTrue (c == 'a');
assertTrue (str.tellg() == std::streampos(11));
str.seekg(-1, std::ios::end);
assertTrue (str.tellg() == std::streampos(15));
c = str.get();
assertTrue (c == 'f');
assertTrue (str.tellg() == std::streampos(16));
str.seekg(-1, std::ios::cur);
assertTrue (str.tellg() == std::streampos(15));
c = str.get();
assertTrue (c == 'f');
assertTrue (str.tellg() == std::streampos(16));
str.seekg(-4, std::ios::cur);
assertTrue (str.tellg() == std::streampos(12));
c = str.get();
assertTrue (c == 'c');
assertTrue (str.tellg() == std::streampos(13));
str.seekg(1, std::ios::cur);
assertTrue (str.tellg() == std::streampos(14));
c = str.get();
assertTrue (c == 'e');
assertTrue (str.tellg() == std::streampos(15));
}
void FileStreamTest::testMultiOpen()
{
Poco::FileStream str("test.txt", std::ios::trunc);
str << "0123456789\n";
str << "abcdefghij\n";
str << "klmnopqrst\n";
str.close();
std::string s;
str.open("test.txt", std::ios::in);
std::getline(str, s);
assertTrue (s == "0123456789");
str.close();
str.open("test.txt", std::ios::in);
std::getline(str, s);
assertTrue (s == "0123456789");
str.close();
}
void FileStreamTest::setUp()
{
}
void FileStreamTest::tearDown()
{
}
CppUnit::Test* FileStreamTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FileStreamTest");
CppUnit_addTest(pSuite, FileStreamTest, testRead);
CppUnit_addTest(pSuite, FileStreamTest, testWrite);
CppUnit_addTest(pSuite, FileStreamTest, testReadWrite);
CppUnit_addTest(pSuite, FileStreamTest, testOpen);
CppUnit_addTest(pSuite, FileStreamTest, testOpenModeIn);
CppUnit_addTest(pSuite, FileStreamTest, testOpenModeOut);
CppUnit_addTest(pSuite, FileStreamTest, testOpenModeTrunc);
CppUnit_addTest(pSuite, FileStreamTest, testOpenModeAte);
CppUnit_addTest(pSuite, FileStreamTest, testOpenModeApp);
CppUnit_addTest(pSuite, FileStreamTest, testSeek);
CppUnit_addTest(pSuite, FileStreamTest, testMultiOpen);
return pSuite;
}

View File

@@ -0,0 +1,48 @@
//
// FileStreamTest.h
//
// Definition of the FileStreamTest class.
//
// Copyright (c) 2007, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef FileStreamTest_INCLUDED
#define FileStreamTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class FileStreamTest: public CppUnit::TestCase
{
public:
FileStreamTest(const std::string& name);
~FileStreamTest();
void testRead();
void testWrite();
void testReadWrite();
void testOpen();
void testOpenModeIn();
void testOpenModeOut();
void testOpenModeTrunc();
void testOpenModeAte();
void testOpenModeApp();
void testSeek();
void testMultiOpen();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // FileStreamTest_INCLUDED

View File

@@ -0,0 +1,659 @@
//
// FileTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "FileTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/File.h"
#include "Poco/TemporaryFile.h"
#include "Poco/Path.h"
#include "Poco/Exception.h"
#include "Poco/Thread.h"
#include <fstream>
#include <set>
using Poco::File;
using Poco::TemporaryFile;
using Poco::Path;
using Poco::Exception;
using Poco::Timestamp;
using Poco::Thread;
FileTest::FileTest(const std::string& name): CppUnit::TestCase(name)
{
}
FileTest::~FileTest()
{
}
void FileTest::testFileAttributes1()
{
File f("testfile.dat");
assertTrue (!f.exists());
try
{
bool POCO_UNUSED flag = f.canRead();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
bool POCO_UNUSED flag = f.canWrite();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
bool POCO_UNUSED flag = f.isFile();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
bool POCO_UNUSED flag = f.isDirectory();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
Timestamp POCO_UNUSED ts = f.created();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
Timestamp POCO_UNUSED ts = f.getLastModified();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
Timestamp ts;
f.setLastModified(ts);
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
File::FileSize POCO_UNUSED fs = f.getSize();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
f.setSize(0);
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
f.setWriteable();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
f.setReadOnly();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
f.copyTo("copy.dat");
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
f.moveTo("copy.dat");
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
f.renameTo("copy.dat");
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
try
{
f.remove();
failmsg("file does not exist - must throw exception");
}
catch (Exception&)
{
}
}
void FileTest::testCreateFile()
{
File f("testfile.dat");
bool created = f.createFile();
assertTrue (created);
assertTrue (!f.isHidden());
created = f.createFile();
assertTrue (!created);
}
void FileTest::testFileAttributes2()
{
TemporaryFile f;
bool created = f.createFile();
Timestamp ts;
assertTrue (created);
assertTrue (f.exists());
assertTrue (f.canRead());
assertTrue (f.canWrite());
assertTrue (f.isFile());
assertTrue (!f.isDirectory());
Timestamp tsc = f.created();
Timestamp tsm = f.getLastModified();
assertTrue (tsc - ts >= -2000000 && tsc - ts <= 2000000);
assertTrue (tsm - ts >= -2000000 && tsm - ts <= 2000000);
f.setWriteable(false);
assertTrue (!f.canWrite());
assertTrue (f.canRead());
f.setReadOnly(false);
assertTrue (f.canWrite());
assertTrue (f.canRead());
ts = Timestamp::fromEpochTime(1000000);
f.setLastModified(ts);
assertTrue (f.getLastModified() == ts);
}
void FileTest::testFileAttributes3()
{
#if defined(POCO_OS_FAMILY_UNIX)
#if POCO_OS==POCO_OS_CYGWIN
File f("/dev/tty");
#else
File f("/dev/console");
#endif
#elif defined(POCO_OS_FAMILY_WINDOWS) && !defined(_WIN32_WCE)
File f("CON");
#endif
#if !defined(_WIN32_WCE)
assertTrue (f.isDevice());
assertTrue (!f.isFile());
assertTrue (!f.isDirectory());
#endif
}
void FileTest::testCompare()
{
File f1("abc.txt");
File f2("def.txt");
File f3("abc.txt");
assertTrue (f1 == f3);
assertTrue (!(f1 == f2));
assertTrue (f1 != f2);
assertTrue (!(f1 != f3));
assertTrue (!(f1 == f2));
assertTrue (f1 < f2);
assertTrue (f1 <= f2);
assertTrue (!(f2 < f1));
assertTrue (!(f2 <= f1));
assertTrue (f2 > f1);
assertTrue (f2 >= f1);
assertTrue (!(f1 > f2));
assertTrue (!(f1 >= f2));
assertTrue (f1 <= f3);
assertTrue (f1 >= f3);
}
void FileTest::testRootDir()
{
#if defined(POCO_OS_FAMILY_WINDOWS)
#if defined(_WIN32_WCE)
File f1("\\");
File f2("/");
assertTrue (f1.exists());
assertTrue (f2.exists());
#else
File f1("/");
File f2("c:/");
File f3("c:\\");
File f4("\\");
assertTrue (f1.exists());
assertTrue (f2.exists());
assertTrue (f3.exists());
assertTrue (f4.exists());
#endif
#else
File f1("/");
assertTrue (f1.exists());
#endif
}
void FileTest::testSwap()
{
File f1("abc.txt");
File f2("def.txt");
f1.swap(f2);
assertTrue (f1.path() == "def.txt");
assertTrue (f2.path() == "abc.txt");
}
void FileTest::testSize()
{
std::ofstream ostr("testfile.dat");
ostr << "Hello, world!" << std::endl;
ostr.close();
File f("testfile.dat");
assertTrue (f.getSize() > 0);
f.setSize(0);
assertTrue (f.getSize() == 0);
}
void FileTest::testDirectory()
{
File d("testdir");
try
{
d.remove(true);
}
catch (...)
{
}
TemporaryFile::registerForDeletion("testdir");
bool created = d.createDirectory();
assertTrue (created);
assertTrue (d.isDirectory());
assertTrue (!d.isFile());
std::vector<std::string> files;
d.list(files);
assertTrue (files.empty());
File f = Path("testdir/file1", Path::PATH_UNIX);
f.createFile();
f = Path("testdir/file2", Path::PATH_UNIX);
f.createFile();
f = Path("testdir/file3", Path::PATH_UNIX);
f.createFile();
d.list(files);
assertTrue (files.size() == 3);
std::set<std::string> fs;
fs.insert(files.begin(), files.end());
assertTrue (fs.find("file1") != fs.end());
assertTrue (fs.find("file2") != fs.end());
assertTrue (fs.find("file3") != fs.end());
File dd(Path("testdir/testdir2/testdir3", Path::PATH_UNIX));
dd.createDirectories();
assertTrue (dd.exists());
assertTrue (dd.isDirectory());
File ddd(Path("testdir/testdirB/testdirC/testdirD", Path::PATH_UNIX));
ddd.createDirectories();
assertTrue (ddd.exists());
assertTrue (ddd.isDirectory());
d.remove(true);
}
void FileTest::testCopy()
{
std::ofstream ostr("testfile.dat");
ostr << "Hello, world!" << std::endl;
ostr.close();
File f1("testfile.dat");
TemporaryFile f2;
f1.setReadOnly().copyTo(f2.path());
assertTrue (f2.exists());
assertTrue (!f2.canWrite());
assertTrue (f1.getSize() == f2.getSize());
f1.setWriteable().remove();
}
void FileTest::testCopyFailIfDestinationFileExists()
{
std::ofstream ostr("testfile.dat");
ostr << "Hello, world!" << std::endl;
ostr.close();
File f1("testfile.dat");
TemporaryFile f2;
f2.createFile();
try {
f1.setReadOnly().copyTo(f2.path(), File::OPT_FAIL_ON_OVERWRITE);
failmsg("file exist - must throw exception");
} catch (Exception&) {
}
f1.setWriteable().remove();
}
void FileTest::testMove()
{
std::ofstream ostr("testfile.dat");
ostr << "Hello, world!" << std::endl;
ostr.close();
File f1("testfile.dat");
File::FileSize sz = f1.getSize();
TemporaryFile f2;
f1.moveTo(f2.path());
assertTrue (f2.exists());
assertTrue (f2.getSize() == sz);
assertTrue (f1.exists());
assertTrue (f1 == f2);
}
void FileTest::testMoveFailIfDestinationFileExists() {
std::ofstream ostr("testfile.dat");
ostr << "Hello, world!" << std::endl;
ostr.close();
File f1("testfile.dat");
TemporaryFile f2;
f2.createFile();
try {
f1.moveTo(f2.path(), File::OPT_FAIL_ON_OVERWRITE);
failmsg("file exist - must throw exception");
} catch (Exception&) {
}
f1.setWriteable().remove();
}
void FileTest::testCopyDirectory()
{
Path pd1("testdir");
File fd1(pd1);
try
{
fd1.remove(true);
}
catch (...)
{
}
fd1.createDirectories();
Path pd2(pd1, "subdir");
File fd2(pd2);
fd2.createDirectories();
Path pf1(pd1, "testfile1.dat");
std::ofstream ostr1(pf1.toString().c_str());
ostr1 << "Hello, world!" << std::endl;
ostr1.close();
Path pf2(pd1, "testfile2.dat");
std::ofstream ostr2(pf2.toString().c_str());
ostr2 << "Hello, world!" << std::endl;
ostr2.close();
Path pf3(pd2, "testfile3.dat");
std::ofstream ostr3(pf3.toString().c_str());
ostr3 << "Hello, world!" << std::endl;
ostr3.close();
File fd3("testdir2");
try
{
fd3.remove(true);
}
catch (...)
{
}
fd1.copyTo("testdir2");
Path pd1t("testdir2");
File fd1t(pd1t);
assertTrue (fd1t.exists());
assertTrue (fd1t.isDirectory());
Path pd2t(pd1t, "subdir");
File fd2t(pd2t);
assertTrue (fd2t.exists());
assertTrue (fd2t.isDirectory());
Path pf1t(pd1t, "testfile1.dat");
File ff1t(pf1t);
assertTrue (ff1t.exists());
assertTrue (ff1t.isFile());
Path pf2t(pd1t, "testfile2.dat");
File ff2t(pf2t);
assertTrue (ff2t.exists());
assertTrue (ff2t.isFile());
Path pf3t(pd2t, "testfile3.dat");
File ff3t(pf3t);
assertTrue (ff3t.exists());
assertTrue (ff3t.isFile());
fd1.remove(true);
fd3.remove(true);
}
void FileTest::testCopyDirectoryFailIfExists()
{
Path pd1("testdir");
File fd1(pd1);
try {
fd1.remove(true);
} catch (...) {
}
fd1.createDirectories();
Path pf1(pd1, "testfile1.dat");
std::ofstream ostr1(pf1.toString().c_str());
ostr1 << "Hello, world!" << std::endl;
ostr1.close();
Path pf2(pd1, "testfile2.dat");
std::ofstream ostr2(pf2.toString().c_str());
ostr2 << "Hello, world!" << std::endl;
ostr2.close();
Path pd2("destination");
File fd2(pd2);
try {
fd2.remove(true);
} catch (...) {
}
fd2.createDirectories();
Path pd3(pd2, "testdir");
File fd3(pd3);
fd3.createDirectories();
try {
fd1.copyTo("testdir", File::OPT_FAIL_ON_OVERWRITE);
failmsg("Destination Directory exists - must throw exception");
} catch (Exception&) {
}
fd1.remove(true);
fd2.remove(true);
}
void FileTest::testRename()
{
std::ofstream ostr("testfile.dat");
ostr << "Hello, world!" << std::endl;
ostr.close();
File f1("testfile.dat");
File f2("testfile2.dat");
f1.renameTo(f2.path());
assertTrue (f2.exists());
assertTrue (f1.exists());
assertTrue (f1 == f2);
f2.remove();
}
void FileTest::testRenameFailIfExists() {
std::ofstream ostr("testfile.dat");
ostr << "Hello, world!" << std::endl;
ostr.close();
File f1("testfile.dat");
File f2("testfile2.dat");
f2.createFile();
try {
f1.renameTo(f2.path(), File::OPT_FAIL_ON_OVERWRITE);
failmsg("file exists - must throw exception");
} catch (Exception&) {
}
f1.renameTo(f2.path());
assertTrue(f2.exists());
assertTrue(f1.exists());
assertTrue(f1 == f2);
f2.remove();
}
void FileTest::testLongPath()
{
#if defined(_WIN32) && !defined(_WIN32_WCE)
Poco::Path p("longpathtest");
p.makeAbsolute();
std::string longpath(p.toString());
while (longpath.size() < MAX_PATH*4)
{
longpath.append("\\");
longpath.append(64, 'x');
}
Poco::File d(longpath);
d.createDirectories();
assertTrue (d.exists());
assertTrue (d.isDirectory());
Poco::File f(p.toString());
f.remove(true);
#endif
}
void FileTest::setUp()
{
File f("testfile.dat");
try
{
f.remove();
}
catch (...)
{
}
}
void FileTest::tearDown()
{
File f("testfile.dat");
try
{
f.remove();
}
catch (...)
{
}
}
CppUnit::Test* FileTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FileTest");
CppUnit_addTest(pSuite, FileTest, testCreateFile);
CppUnit_addTest(pSuite, FileTest, testFileAttributes1);
CppUnit_addTest(pSuite, FileTest, testFileAttributes2);
CppUnit_addTest(pSuite, FileTest, testFileAttributes3);
CppUnit_addTest(pSuite, FileTest, testCompare);
CppUnit_addTest(pSuite, FileTest, testSwap);
CppUnit_addTest(pSuite, FileTest, testSize);
CppUnit_addTest(pSuite, FileTest, testDirectory);
CppUnit_addTest(pSuite, FileTest, testCopy);
CppUnit_addTest(pSuite, FileTest, testCopyFailIfDestinationFileExists);
CppUnit_addTest(pSuite, FileTest, testMove);
CppUnit_addTest(pSuite, FileTest, testMoveFailIfDestinationFileExists);
CppUnit_addTest(pSuite, FileTest, testCopyDirectory);
CppUnit_addTest(pSuite, FileTest, testCopyDirectoryFailIfExists);
CppUnit_addTest(pSuite, FileTest, testRename);
CppUnit_addTest(pSuite, FileTest, testRenameFailIfExists);
CppUnit_addTest(pSuite, FileTest, testRootDir);
CppUnit_addTest(pSuite, FileTest, testLongPath);
return pSuite;
}

View File

@@ -0,0 +1,55 @@
//
// FileTest.h
//
// Definition of the FileTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef FileTest_INCLUDED
#define FileTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class FileTest: public CppUnit::TestCase
{
public:
FileTest(const std::string& name);
~FileTest();
void testFileAttributes1();
void testCreateFile();
void testFileAttributes2();
void testFileAttributes3();
void testCompare();
void testSwap();
void testSize();
void testDirectory();
void testCopy();
void testCopyFailIfDestinationFileExists();
void testMove();
void testMoveFailIfDestinationFileExists();
void testCopyDirectory();
void testCopyDirectoryFailIfExists();
void testRename();
void testRenameFailIfExists();
void testRootDir();
void testLongPath();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // FileTest_INCLUDED

View File

@@ -0,0 +1,32 @@
//
// FilesystemTestSuite.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "FilesystemTestSuite.h"
#include "PathTest.h"
#include "FileTest.h"
#include "GlobTest.h"
#include "DirectoryWatcherTest.h"
#include "DirectoryIteratorsTest.h"
CppUnit::Test* FilesystemTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FilesystemTestSuite");
pSuite->addTest(PathTest::suite());
pSuite->addTest(FileTest::suite());
pSuite->addTest(GlobTest::suite());
#ifndef POCO_NO_INOTIFY
pSuite->addTest(DirectoryWatcherTest::suite());
#endif // POCO_NO_INOTIFY
pSuite->addTest(DirectoryIteratorsTest::suite());
return pSuite;
}

View File

@@ -0,0 +1,27 @@
//
// FilesystemTestSuite.h
//
// Definition of the FilesystemTestSuite class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef FilesystemTestSuite_INCLUDED
#define FilesystemTestSuite_INCLUDED
#include "CppUnit/TestSuite.h"
class FilesystemTestSuite
{
public:
static CppUnit::Test* suite();
};
#endif // FilesystemTestSuite_INCLUDED

View File

@@ -0,0 +1,481 @@
//
// FormatTest.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "FormatTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Any.h"
#include "Poco/Format.h"
#include "Poco/Exception.h"
using Poco::format;
using Poco::BadCastException;
using Poco::Int64;
using Poco::UInt64;
FormatTest::FormatTest(const std::string& name): CppUnit::TestCase(name)
{
}
FormatTest::~FormatTest()
{
}
void FormatTest::testChar()
{
char c = 'a';
std::string s(format("%c", c));
assertTrue (s == "a");
s = format("%2c", c);
assertTrue (s == " a");
s = format("%-2c", c);
assertTrue (s == "a ");
s = format("%*c", 2, c);
assertTrue (s == " a");
s = format("%-*c", 2, c);
assertTrue (s == "a ");
s = format("%c", std::string("foo"));
assertTrue (s == "[ERRFMT]");
}
void FormatTest::testInt()
{
int i = 42;
std::string s(format("%d", i));
assertTrue (s == "42");
s = format("%4d", i);
assertTrue (s == " 42");
s = format("%04d", i);
assertTrue (s == "0042");
s = format("%*d", 4, i);
assertTrue (s == " 42");
s = format("%0*d", 4, i);
assertTrue (s == "0042");
short h = 42;
s = format("%hd", h);
assertTrue (s == "42");
s = format("%4hd", h);
assertTrue (s == " 42");
s = format("%04hd", h);
assertTrue (s == "0042");
s = format("%*hd", 4, h);
assertTrue (s == " 42");
s = format("%0*hd", 4, h);
assertTrue (s == "0042");
unsigned short hu = 42;
s = format("%hu", hu);
assertTrue (s == "42");
s = format("%4hu", hu);
assertTrue (s == " 42");
s = format("%04hu", hu);
assertTrue (s == "0042");
s = format("%*hu", 4, hu);
assertTrue (s == " 42");
s = format("%0*hu", 4, hu);
assertTrue (s == "0042");
unsigned x = 0x42;
s = format("%x", x);
assertTrue (s == "42");
s = format("%4x", x);
assertTrue (s == " 42");
s = format("%04x", x);
assertTrue (s == "0042");
s = format("%*x", 4, x);
assertTrue (s == " 42");
s = format("%0*x", 4, x);
assertTrue (s == "0042");
unsigned o = 042;
s = format("%o", o);
assertTrue (s == "42");
s = format("%4o", o);
assertTrue (s == " 42");
s = format("%04o", o);
assertTrue (s == "0042");
s = format("%*o", 4, o);
assertTrue (s == " 42");
s = format("%0*o", 4, o);
assertTrue (s == "0042");
unsigned u = 42;
s = format("%u", u);
assertTrue (s == "42");
s = format("%4u", u);
assertTrue (s == " 42");
s = format("%04u", u);
assertTrue (s == "0042");
s = format("%*u", 4, u);
assertTrue (s == " 42");
s = format("%0*u", 4, u);
assertTrue (s == "0042");
long l = 42;
s = format("%ld", l);
assertTrue (s == "42");
s = format("%4ld", l);
assertTrue (s == " 42");
s = format("%04ld", l);
assertTrue (s == "0042");
s = format("%*ld", 4, l);
assertTrue (s == " 42");
s = format("%0*ld", 4, l);
assertTrue (s == "0042");
unsigned long ul = 42;
s = format("%lu", ul);
assertTrue (s == "42");
s = format("%4lu", ul);
assertTrue (s == " 42");
s = format("%04lu", ul);
assertTrue (s == "0042");
s = format("%*lu", 4, ul);
assertTrue (s == " 42");
s = format("%0*lu", 4, ul);
assertTrue (s == "0042");
unsigned long xl = 0x42;
s = format("%lx", xl);
assertTrue (s == "42");
s = format("%4lx", xl);
assertTrue (s == " 42");
s = format("%04lx", xl);
assertTrue (s == "0042");
s = format("%*lx", 4, xl);
assertTrue (s == " 42");
s = format("%0*lx", 4, xl);
assertTrue (s == "0042");
Int64 i64 = 42;
s = format("%Ld", i64);
assertTrue (s == "42");
s = format("%4Ld", i64);
assertTrue (s == " 42");
s = format("%04Ld", i64);
assertTrue (s == "0042");
s = format("%*Ld", 4, i64);
assertTrue (s == " 42");
s = format("%0*Ld", 4, i64);
assertTrue (s == "0042");
UInt64 ui64 = 42;
s = format("%Lu", ui64);
assertTrue (s == "42");
s = format("%4Lu", ui64);
assertTrue (s == " 42");
s = format("%04Lu", ui64);
assertTrue (s == "0042");
s = format("%*Lu", 4, ui64);
assertTrue (s == " 42");
s = format("%0*Lu", 4, ui64);
assertTrue (s == "0042");
x = 0xaa;
s = format("%x", x);
assertTrue (s == "aa");
s = format("%X", x);
assertTrue (s == "AA");
i = 42;
s = format("%+d", i);
assertTrue (s == "+42");
i = -42;
s = format("%+d", i);
assertTrue (s == "-42");
s = format("%+04d", i);
assertTrue (s == "-042");
s = format("%+0*d", 4, i);
assertTrue (s == "-042");
s = format("%d", i);
assertTrue (s == "-42");
s = format("%d", i);
assertTrue (s == "-42");
x = 0x42;
s = format("%#x", x);
assertTrue (s == "0x42");
s = format("%d", l);
assertTrue (s == "[ERRFMT]");
}
void FormatTest::testBool()
{
bool b = true;
std::string s = format("%b", b);
assertTrue (s == "1");
b = false;
s = format("%b", b);
assertTrue (s == "0");
std::vector<Poco::Any> bv;
bv.push_back(false);
bv.push_back(true);
bv.push_back(false);
bv.push_back(true);
bv.push_back(false);
bv.push_back(true);
bv.push_back(false);
bv.push_back(true);
bv.push_back(false);
bv.push_back(true);
s.clear();
format(s, "%b%b%b%b%b%b%b%b%b%b", bv);
assertTrue (s == "0101010101");
}
void FormatTest::testAnyInt()
{
char c = 42;
std::string s(format("%?i", c));
assertTrue (s == "42");
c = 43;
s.clear();
format(s, "%?i", c);
assertTrue (s == "43");
bool b = true;
s = format("%?i", b);
assertTrue (s == "1");
signed char sc = -42;
s = format("%?i", sc);
assertTrue (s == "-42");
unsigned char uc = 65;
s = format("%?i", uc);
assertTrue (s == "65");
short ss = -134;
s = format("%?i", ss);
assertTrue (s == "-134");
unsigned short us = 200;
s = format("%?i", us);
assertTrue (s == "200");
int i = -12345;
s = format("%?i", i);
assertTrue (s == "-12345");
unsigned ui = 12345;
s = format("%?i", ui);
assertTrue (s == "12345");
long l = -54321;
s = format("%?i", l);
assertTrue (s == "-54321");
unsigned long ul = 54321;
s = format("%?i", ul);
assertTrue (s == "54321");
Int64 i64 = -12345678;
s = format("%?i", i64);
assertTrue (s == "-12345678");
UInt64 ui64 = 12345678;
s = format("%?i", ui64);
assertTrue (s == "12345678");
ss = 0x42;
s = format("%?x", ss);
assertTrue (s == "42");
ss = 042;
s = format("%?o", ss);
assertTrue (s == "42");
}
void FormatTest::testFloatFix()
{
double d = 1.5;
std::string s(format("%f", d));
assertTrue (s.find("1.50") == 0);
s = format("%10f", d);
assertTrue (s.find(" 1.50") != std::string::npos);
s = format("%*f", 10, d);
assertTrue (s.find(" 1.50") != std::string::npos);
s = format("%6.2f", d);
assertTrue (s == " 1.50");
s = format("%-6.2f", d);
assertTrue (s == "1.50 ");
s = format("%*.*f", 6, 2, d);
assertTrue (s == " 1.50");
s = format("%-*.*f", 6,2, d);
assertTrue (s == "1.50 ");
float f = 1.5;
s = format("%hf", f);
assertTrue (s.find("1.50") == 0);
s = format("%.0f", 1.0);
assertTrue (s == "1");
s = format("%.*f", 0, 1.0);
assertTrue (s == "1");
}
void FormatTest::testFloatSci()
{
double d = 1.5;
std::string s(format("%e", d));
assertTrue (s.find("1.50") == 0);
assertTrue (s.find("0e+0") != std::string::npos);
s = format("%20e", d);
assertTrue (s.find(" 1.50") != std::string::npos);
assertTrue (s.find("0e+0") != std::string::npos);
s = format("%*e", 20, d);
assertTrue (s.find(" 1.50") != std::string::npos);
assertTrue (s.find("0e+0") != std::string::npos);
s = format("%10.2e", d);
assertTrue (s == " 1.50e+000" || s == " 1.50e+00");
s = format("%-10.2e", d);
assertTrue (s == "1.50e+000 " || s == "1.50e+00 ");
s = format("%-10.2E", d);
assertTrue (s == "1.50E+000 " || s == "1.50E+00 ");
s = format("%*.*e", 10, 2, d);
assertTrue (s == " 1.50e+000" || s == " 1.50e+00");
s = format("%-*.*e", 10, 2, d);
assertTrue (s == "1.50e+000 " || s == "1.50e+00 ");
s = format("%-*.*E", 10, 2, d);
assertTrue (s == "1.50E+000 " || s == "1.50E+00 ");
}
void FormatTest::testString()
{
std::string foo("foo");
std::string s(format("%s", foo));
assertTrue (s == "foo");
s = format("%5s", foo);
assertTrue (s == " foo");
s = format("%-5s", foo);
assertTrue (s == "foo ");
s = format("%*s", 5, foo);
assertTrue (s == " foo");
s = format("%-*s", 5, foo);
assertTrue (s == "foo ");
s = format("%s%%a", foo);
assertTrue (s == "foo%a");
s = format("'%s%%''%s%%'", foo, foo);
assertTrue (s == "'foo%''foo%'");
}
void FormatTest::testMultiple()
{
std::string s(format("aaa%dbbb%4dccc", 1, 2));
assertTrue (s == "aaa1bbb 2ccc");
s = format("%%%d%%%d%%%d", 1, 2, 3);
assertTrue (s == "%1%2%3");
s = format("%d%d%d%d", 1, 2, 3, 4);
assertTrue (s == "1234");
s = format("%d%d%d%d%d", 1, 2, 3, 4, 5);
assertTrue (s == "12345");
s = format("%d%d%d%d%d%d", 1, 2, 3, 4, 5, 6);
assertTrue (s == "123456");
s = format("%d%d%d%d%d%d%d%d%d%d", 1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
assertTrue (s == "1234567890");
}
void FormatTest::testIndex()
{
std::string s(format("%[1]d%[0]d", 1, 2));
assertTrue (s == "21");
s = format("%[5]d%[4]d%[3]d%[2]d%[1]d%[0]d", 1, 2, 3, 4, 5, 6);
assertTrue (s == "654321");
s = format("%%%[1]d%%%[2]d%%%d", 1, 2, 3);
assertTrue (s == "%2%3%1");
s = format("%%%d%%%d%%%[0]d", 1, 2);
assertTrue (s == "%1%2%1");
}
void FormatTest::setUp()
{
}
void FormatTest::tearDown()
{
}
CppUnit::Test* FormatTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FormatTest");
CppUnit_addTest(pSuite, FormatTest, testChar);
CppUnit_addTest(pSuite, FormatTest, testBool);
CppUnit_addTest(pSuite, FormatTest, testInt);
CppUnit_addTest(pSuite, FormatTest, testAnyInt);
CppUnit_addTest(pSuite, FormatTest, testFloatFix);
CppUnit_addTest(pSuite, FormatTest, testFloatSci);
CppUnit_addTest(pSuite, FormatTest, testString);
CppUnit_addTest(pSuite, FormatTest, testMultiple);
CppUnit_addTest(pSuite, FormatTest, testIndex);
return pSuite;
}

View File

@@ -0,0 +1,43 @@
//
// FormatTest.h
//
// Definition of the FormatTest class.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef FormatTest_INCLUDED
#define FormatTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class FormatTest: public CppUnit::TestCase
{
public:
FormatTest(const std::string& name);
~FormatTest();
void testChar();
void testInt();
void testBool();
void testAnyInt();
void testFloatFix();
void testFloatSci();
void testString();
void testMultiple();
void testIndex();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // FormatTest_INCLUDED

View File

@@ -0,0 +1,58 @@
//
// FoundationTestSuite.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "FoundationTestSuite.h"
#include "CoreTestSuite.h"
#include "DateTimeTestSuite.h"
#include "StreamsTestSuite.h"
#include "CryptTestSuite.h"
#include "NotificationsTestSuite.h"
#include "ThreadingTestSuite.h"
#include "SharedLibraryTestSuite.h"
#include "LoggingTestSuite.h"
#include "FilesystemTestSuite.h"
#include "UUIDTestSuite.h"
#include "TextTestSuite.h"
#include "URITestSuite.h"
#if !defined(POCO_VXWORKS)
#include "ProcessesTestSuite.h"
#endif
#include "TaskTestSuite.h"
#include "EventTestSuite.h"
#include "CacheTestSuite.h"
#include "HashingTestSuite.h"
CppUnit::Test* FoundationTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("FoundationTestSuite");
pSuite->addTest(CoreTestSuite::suite());
pSuite->addTest(DateTimeTestSuite::suite());
pSuite->addTest(StreamsTestSuite::suite());
pSuite->addTest(CryptTestSuite::suite());
pSuite->addTest(NotificationsTestSuite::suite());
pSuite->addTest(ThreadingTestSuite::suite());
pSuite->addTest(SharedLibraryTestSuite::suite());
pSuite->addTest(LoggingTestSuite::suite());
pSuite->addTest(FilesystemTestSuite::suite());
pSuite->addTest(UUIDTestSuite::suite());
pSuite->addTest(TextTestSuite::suite());
pSuite->addTest(URITestSuite::suite());
#if !defined(POCO_VXWORKS)
pSuite->addTest(ProcessesTestSuite::suite());
#endif
pSuite->addTest(TaskTestSuite::suite());
pSuite->addTest(EventTestSuite::suite());
pSuite->addTest(CacheTestSuite::suite());
pSuite->addTest(HashingTestSuite::suite());
return pSuite;
}

View File

@@ -0,0 +1,27 @@
//
// FoundationTestSuite.h
//
// Definition of the FoundationTestSuite class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef FoundationTestSuite_INCLUDED
#define FoundationTestSuite_INCLUDED
#include "CppUnit/TestSuite.h"
class FoundationTestSuite
{
public:
static CppUnit::Test* suite();
};
#endif // FoundationTestSuite_INCLUDED

View File

@@ -0,0 +1,535 @@
//
// GlobTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "GlobTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Glob.h"
#include "Poco/File.h"
#include "Poco/Path.h"
#include <fstream>
using Poco::Glob;
using Poco::File;
using Poco::Path;
GlobTest::GlobTest(const std::string& name): CppUnit::TestCase(name)
{
}
GlobTest::~GlobTest()
{
}
void GlobTest::testMatchChars()
{
Glob g1("a");
assertTrue (g1.match("a"));
assertTrue (!g1.match("b"));
assertTrue (!g1.match("aa"));
assertTrue (!g1.match(""));
Glob g2("ab");
assertTrue (g2.match("ab"));
assertTrue (!g2.match("aab"));
assertTrue (!g2.match("abab"));
}
void GlobTest::testMatchQM()
{
Glob g1("?");
assertTrue (g1.match("a"));
assertTrue (g1.match("b"));
assertTrue (!g1.match("aa"));
assertTrue (g1.match("."));
Glob g2("\\?");
assertTrue (g2.match("?"));
assertTrue (!g2.match("a"));
assertTrue (!g2.match("ab"));
Glob g3("a?");
assertTrue (g3.match("aa"));
assertTrue (g3.match("az"));
assertTrue (!g3.match("a"));
assertTrue (!g3.match("aaa"));
Glob g4("??");
assertTrue (g4.match("aa"));
assertTrue (g4.match("ab"));
assertTrue (!g4.match("a"));
assertTrue (!g4.match("abc"));
Glob g5("?a?");
assertTrue (g5.match("aaa"));
assertTrue (g5.match("bac"));
assertTrue (!g5.match("bbc"));
assertTrue (!g5.match("ba"));
assertTrue (!g5.match("ab"));
Glob g6("a\\?");
assertTrue (g6.match("a?"));
assertTrue (!g6.match("az"));
assertTrue (!g6.match("a"));
Glob g7("?", Glob::GLOB_DOT_SPECIAL);
assertTrue (g7.match("a"));
assertTrue (g7.match("b"));
assertTrue (!g7.match("aa"));
assertTrue (!g7.match("."));
}
void GlobTest::testMatchAsterisk()
{
Glob g1("*");
assertTrue (g1.match(""));
assertTrue (g1.match("a"));
assertTrue (g1.match("ab"));
assertTrue (g1.match("abc"));
assertTrue (g1.match("."));
Glob g2("a*");
assertTrue (g2.match("a"));
assertTrue (g2.match("aa"));
assertTrue (g2.match("abc"));
assertTrue (!g2.match("b"));
assertTrue (!g2.match("ba"));
Glob g3("ab*");
assertTrue (g3.match("ab"));
assertTrue (g3.match("abc"));
assertTrue (g3.match("abab"));
assertTrue (!g3.match("ac"));
assertTrue (!g3.match("baab"));
Glob g4("*a");
assertTrue (g4.match("a"));
assertTrue (g4.match("ba"));
assertTrue (g4.match("aa"));
assertTrue (g4.match("aaaaaa"));
assertTrue (g4.match("bbbbba"));
assertTrue (!g4.match("b"));
assertTrue (!g4.match("ab"));
assertTrue (!g4.match("aaab"));
Glob g5("a*a");
assertTrue (g5.match("aa"));
assertTrue (g5.match("aba"));
assertTrue (g5.match("abba"));
assertTrue (!g5.match("aab"));
assertTrue (!g5.match("aaab"));
assertTrue (!g5.match("baaaa"));
Glob g6("a*b*c");
assertTrue (g6.match("abc"));
assertTrue (g6.match("aabbcc"));
assertTrue (g6.match("abcbbc"));
assertTrue (g6.match("aaaabbbbcccc"));
assertTrue (!g6.match("aaaabbbcb"));
Glob g7("a*b*");
assertTrue (g7.match("aaabbb"));
assertTrue (g7.match("abababab"));
assertTrue (g7.match("ab"));
assertTrue (g7.match("aaaaab"));
assertTrue (!g7.match("a"));
assertTrue (!g7.match("aa"));
assertTrue (!g7.match("aaa"));
Glob g8("**");
assertTrue (g1.match(""));
assertTrue (g1.match("a"));
assertTrue (g1.match("ab"));
assertTrue (g1.match("abc"));
Glob g9("a\\*");
assertTrue (g9.match("a*"));
assertTrue (!g9.match("aa"));
assertTrue (!g9.match("a"));
Glob g10("a*\\*");
assertTrue (g10.match("a*"));
assertTrue (g10.match("aaa*"));
assertTrue (!g10.match("a"));
assertTrue (!g10.match("aa"));
Glob g11("*", Glob::GLOB_DOT_SPECIAL);
assertTrue (g11.match(""));
assertTrue (g11.match("a"));
assertTrue (g11.match("ab"));
assertTrue (g11.match("abc"));
assertTrue (!g11.match("."));
}
void GlobTest::testMatchRange()
{
Glob g1("[a]");
assertTrue (g1.match("a"));
assertTrue (!g1.match("b"));
assertTrue (!g1.match("aa"));
Glob g2("[ab]");
assertTrue (g2.match("a"));
assertTrue (g2.match("b"));
assertTrue (!g2.match("c"));
assertTrue (!g2.match("ab"));
Glob g3("[abc]");
assertTrue (g3.match("a"));
assertTrue (g3.match("b"));
assertTrue (g3.match("c"));
assertTrue (!g3.match("ab"));
Glob g4("[a-z]");
assertTrue (g4.match("a"));
assertTrue (g4.match("z"));
assertTrue (!g4.match("A"));
Glob g5("[!a]");
assertTrue (g5.match("b"));
assertTrue (g5.match("c"));
assertTrue (!g5.match("a"));
assertTrue (!g5.match("bb"));
Glob g6("[!a-z]");
assertTrue (g6.match("A"));
assertTrue (!g6.match("a"));
assertTrue (!g6.match("z"));
Glob g7("[0-9a-zA-Z_]");
assertTrue (g7.match("0"));
assertTrue (g7.match("1"));
assertTrue (g7.match("8"));
assertTrue (g7.match("9"));
assertTrue (g7.match("a"));
assertTrue (g7.match("b"));
assertTrue (g7.match("z"));
assertTrue (g7.match("A"));
assertTrue (g7.match("Z"));
assertTrue (g7.match("_"));
assertTrue (!g7.match("-"));
Glob g8("[1-3]");
assertTrue (g8.match("1"));
assertTrue (g8.match("2"));
assertTrue (g8.match("3"));
assertTrue (!g8.match("0"));
assertTrue (!g8.match("4"));
Glob g9("[!1-3]");
assertTrue (g9.match("0"));
assertTrue (g9.match("4"));
assertTrue (!g9.match("1"));
assertTrue (!g9.match("2"));
assertTrue (!g9.match("3"));
Glob g10("[\\!a]");
assertTrue (g10.match("!"));
assertTrue (g10.match("a"));
assertTrue (!g10.match("x"));
Glob g11("[a\\-c]");
assertTrue (g11.match("a"));
assertTrue (g11.match("c"));
assertTrue (g11.match("-"));
assertTrue (!g11.match("b"));
Glob g12("[\\]]");
assertTrue (g12.match("]"));
assertTrue (!g12.match("["));
Glob g13("[[\\]]");
assertTrue (g13.match("["));
assertTrue (g13.match("]"));
assertTrue (!g13.match("x"));
Glob g14("\\[]");
assertTrue (g14.match("[]"));
assertTrue (!g14.match("[["));
Glob g15("a[bc]");
assertTrue (g15.match("ab"));
assertTrue (g15.match("ac"));
assertTrue (!g15.match("a"));
assertTrue (!g15.match("aa"));
Glob g16("[ab]c");
assertTrue (g16.match("ac"));
assertTrue (g16.match("bc"));
assertTrue (!g16.match("a"));
assertTrue (!g16.match("b"));
assertTrue (!g16.match("c"));
assertTrue (!g16.match("aa"));
}
void GlobTest::testMisc()
{
Glob g1("*.cpp");
assertTrue (g1.match("Glob.cpp"));
assertTrue (!g1.match("Glob.h"));
Glob g2("*.[hc]");
assertTrue (g2.match("foo.c"));
assertTrue (g2.match("foo.h"));
assertTrue (!g2.match("foo.i"));
Glob g3("*.*");
assertTrue (g3.match("foo.cpp"));
assertTrue (g3.match("foo.h"));
assertTrue (g3.match("foo."));
assertTrue (!g3.match("foo"));
Glob g4("File*.?pp");
assertTrue (g4.match("File.hpp"));
assertTrue (g4.match("File.cpp"));
assertTrue (g4.match("Filesystem.hpp"));
assertTrue (!g4.match("File.h"));
Glob g5("File*.[ch]*");
assertTrue (g5.match("File.hpp"));
assertTrue (g5.match("File.cpp"));
assertTrue (g5.match("Filesystem.hpp"));
assertTrue (g5.match("File.h"));
assertTrue (g5.match("Filesystem.cp"));
}
void GlobTest::testCaseless()
{
Glob g1("*.cpp", Glob::GLOB_CASELESS);
assertTrue (g1.match("Glob.cpp"));
assertTrue (!g1.match("Glob.h"));
assertTrue (g1.match("Glob.CPP"));
assertTrue (!g1.match("Glob.H"));
Glob g2("*.[hc]", Glob::GLOB_CASELESS);
assertTrue (g2.match("foo.c"));
assertTrue (g2.match("foo.h"));
assertTrue (!g2.match("foo.i"));
assertTrue (g2.match("foo.C"));
assertTrue (g2.match("foo.H"));
assertTrue (!g2.match("foo.I"));
Glob g4("File*.?pp", Glob::GLOB_CASELESS);
assertTrue (g4.match("file.hpp"));
assertTrue (g4.match("FILE.CPP"));
assertTrue (g4.match("filesystem.hpp"));
assertTrue (g4.match("FILESYSTEM.HPP"));
assertTrue (!g4.match("FILE.H"));
assertTrue (!g4.match("file.h"));
Glob g5("File*.[ch]*", Glob::GLOB_CASELESS);
assertTrue (g5.match("file.hpp"));
assertTrue (g5.match("FILE.HPP"));
assertTrue (g5.match("file.cpp"));
assertTrue (g5.match("FILE.CPP"));
assertTrue (g5.match("filesystem.hpp"));
assertTrue (g5.match("FILESYSTEM.HPP"));
assertTrue (g5.match("file.h"));
assertTrue (g5.match("FILE.H"));
assertTrue (g5.match("filesystem.cp"));
assertTrue (g5.match("FILESYSTEM.CP"));
Glob g6("[abc]", Glob::GLOB_CASELESS);
assertTrue (g6.match("a"));
assertTrue (g6.match("b"));
assertTrue (g6.match("c"));
assertTrue (g6.match("A"));
assertTrue (g6.match("B"));
assertTrue (g6.match("C"));
Glob g7("[a-f]", Glob::GLOB_CASELESS);
assertTrue (g7.match("a"));
assertTrue (g7.match("b"));
assertTrue (g7.match("f"));
assertTrue (!g7.match("g"));
assertTrue (g7.match("A"));
assertTrue (g7.match("B"));
assertTrue (g7.match("F"));
assertTrue (!g7.match("G"));
Glob g8("[A-F]", Glob::GLOB_CASELESS);
assertTrue (g8.match("a"));
assertTrue (g8.match("b"));
assertTrue (g8.match("f"));
assertTrue (!g8.match("g"));
assertTrue (g8.match("A"));
assertTrue (g8.match("B"));
assertTrue (g8.match("F"));
assertTrue (!g8.match("G"));
}
void GlobTest::testGlob()
{
createFile("globtest/Makefile");
createFile("globtest/.hidden");
createFile("globtest/include/one.h");
createFile("globtest/include/two.h");
createFile("globtest/src/one.c");
createFile("globtest/src/two.c");
createFile("globtest/src/main.c");
createFile("globtest/testsuite/src/test.h");
createFile("globtest/testsuite/src/test.c");
createFile("globtest/testsuite/src/main.c");
std::set<std::string> files;
Glob::glob("globtest/*", files);
translatePaths(files);
assertTrue (files.size() == 5);
assertTrue (files.find("globtest/Makefile") != files.end());
assertTrue (files.find("globtest/.hidden") != files.end());
assertTrue (files.find("globtest/include/") != files.end());
assertTrue (files.find("globtest/src/") != files.end());
assertTrue (files.find("globtest/testsuite/") != files.end());
files.clear();
Glob::glob("GlobTest/*", files, Glob::GLOB_CASELESS);
translatePaths(files);
assertTrue (files.size() == 5);
assertTrue (files.find("globtest/Makefile") != files.end());
assertTrue (files.find("globtest/.hidden") != files.end());
assertTrue (files.find("globtest/include/") != files.end());
assertTrue (files.find("globtest/src/") != files.end());
assertTrue (files.find("globtest/testsuite/") != files.end());
files.clear();
Glob::glob("globtest/*/*.[hc]", files);
translatePaths(files);
assertTrue (files.size() == 5);
assertTrue (files.find("globtest/include/one.h") != files.end());
assertTrue (files.find("globtest/include/two.h") != files.end());
assertTrue (files.find("globtest/src/one.c") != files.end());
assertTrue (files.find("globtest/src/one.c") != files.end());
assertTrue (files.find("globtest/src/main.c") != files.end());
files.clear();
Glob::glob("gl?bt?st/*/*/*.c", files);
translatePaths(files);
assertTrue (files.size() == 2);
assertTrue (files.find("globtest/testsuite/src/test.c") != files.end());
assertTrue (files.find("globtest/testsuite/src/main.c") != files.end());
files.clear();
Glob::glob("Gl?bT?st/*/*/*.C", files, Glob::GLOB_CASELESS);
translatePaths(files);
assertTrue (files.size() == 2);
assertTrue (files.find("globtest/testsuite/src/test.c") != files.end());
assertTrue (files.find("globtest/testsuite/src/main.c") != files.end());
files.clear();
Glob::glob("globtest/*/src/*", files);
translatePaths(files);
assertTrue (files.size() == 3);
assertTrue (files.find("globtest/testsuite/src/test.h") != files.end());
assertTrue (files.find("globtest/testsuite/src/test.c") != files.end());
assertTrue (files.find("globtest/testsuite/src/main.c") != files.end());
files.clear();
Glob::glob("globtest/*/", files);
translatePaths(files);
assertTrue (files.size() == 3);
assertTrue (files.find("globtest/include/") != files.end());
assertTrue (files.find("globtest/src/") != files.end());
assertTrue (files.find("globtest/testsuite/") != files.end());
files.clear();
Glob::glob("globtest/testsuite/src/*", "globtest/testsuite/", files);
translatePaths(files);
assertTrue (files.size() == 3);
assertTrue (files.find("globtest/testsuite/src/test.h") != files.end());
assertTrue (files.find("globtest/testsuite/src/test.c") != files.end());
assertTrue (files.find("globtest/testsuite/src/main.c") != files.end());
#if !defined(_WIN32_WCE)
// won't work if current directory is root dir
files.clear();
Glob::glob("globtest/../*/testsuite/*/", files);
translatePaths(files);
assertTrue (files.size() == 1);
#endif
File dir("globtest");
dir.remove(true);
}
void GlobTest::testMatchEmptyPattern()
{
// Run the empty pattern against a number of subjects with all different match options
const std::string empty;
assertTrue (!Glob(empty, Glob::GLOB_DEFAULT).match("subject"));
assertTrue (Glob(empty, Glob::GLOB_DEFAULT).match(empty));
assertTrue (!Glob(empty, Glob::GLOB_DOT_SPECIAL).match("subject"));
assertTrue (Glob(empty, Glob::GLOB_DOT_SPECIAL).match(empty));
assertTrue (!Glob(empty, Glob::GLOB_CASELESS).match("subject"));
assertTrue (Glob(empty, Glob::GLOB_CASELESS).match(empty));
}
void GlobTest::createFile(const std::string& path)
{
Path p(path, Path::PATH_UNIX);
File dir(p.parent());
dir.createDirectories();
std::ofstream ostr(path.c_str());
ostr << path << std::endl;
}
void GlobTest::translatePaths(std::set<std::string>& paths)
{
std::set<std::string> translated;
for (std::set<std::string>::const_iterator it = paths.begin(); it != paths.end(); ++it)
{
Path p(*it);
std::string tp(p.toString(Path::PATH_UNIX));
translated.insert(tp);
}
paths = translated;
}
void GlobTest::setUp()
{
}
void GlobTest::tearDown()
{
}
CppUnit::Test* GlobTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("GlobTest");
CppUnit_addTest(pSuite, GlobTest, testMatchChars);
CppUnit_addTest(pSuite, GlobTest, testMatchQM);
CppUnit_addTest(pSuite, GlobTest, testMatchAsterisk);
CppUnit_addTest(pSuite, GlobTest, testMatchRange);
CppUnit_addTest(pSuite, GlobTest, testMisc);
CppUnit_addTest(pSuite, GlobTest, testCaseless);
CppUnit_addTest(pSuite, GlobTest, testGlob);
CppUnit_addTest(pSuite, GlobTest, testMatchEmptyPattern);
return pSuite;
}

View File

@@ -0,0 +1,48 @@
//
// GlobTest.h
//
// Definition of the GlobTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef GlobTest_INCLUDED
#define GlobTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
#include <set>
class GlobTest: public CppUnit::TestCase
{
public:
GlobTest(const std::string& name);
~GlobTest();
void testMatchChars();
void testMatchQM();
void testMatchAsterisk();
void testMatchRange();
void testMisc();
void testGlob();
void testCaseless();
void testMatchEmptyPattern();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
void createFile(const std::string& path);
void translatePaths(std::set<std::string>& paths);
};
#endif // GlobTest_INCLUDED

View File

@@ -0,0 +1,77 @@
//
// HMACEngineTest.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "HMACEngineTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/HMACEngine.h"
#include "Poco/MD5Engine.h"
using Poco::HMACEngine;
using Poco::MD5Engine;
using Poco::DigestEngine;
HMACEngineTest::HMACEngineTest(const std::string& name): CppUnit::TestCase(name)
{
}
HMACEngineTest::~HMACEngineTest()
{
}
void HMACEngineTest::testHMAC()
{
// test vectors from RFC 2104
std::string key(16, 0x0b);
std::string data("Hi There");
HMACEngine<MD5Engine> hmac1(key);
hmac1.update(data);
std::string digest = DigestEngine::digestToHex(hmac1.digest());
assertTrue (digest == "9294727a3638bb1c13f48ef8158bfc9d");
key = "Jefe";
data = "what do ya want for nothing?";
HMACEngine<MD5Engine> hmac2(key);
hmac2.update(data);
digest = DigestEngine::digestToHex(hmac2.digest());
assertTrue (digest == "750c783e6ab0b503eaa86e310a5db738");
key = std::string(16, std::string::value_type(0xaa));
data = std::string(50, std::string::value_type(0xdd));
HMACEngine<MD5Engine> hmac3(key);
hmac3.update(data);
digest = DigestEngine::digestToHex(hmac3.digest());
assertTrue (digest == "56be34521d144c88dbb8c733f0e8b3f6");
}
void HMACEngineTest::setUp()
{
}
void HMACEngineTest::tearDown()
{
}
CppUnit::Test* HMACEngineTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HMACEngineTest");
CppUnit_addTest(pSuite, HMACEngineTest, testHMAC);
return pSuite;
}

View File

@@ -0,0 +1,38 @@
//
// HMACEngineTest.h
//
// Definition of the HMACEngineTest class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef HMACEngineTest_INCLUDED
#define HMACEngineTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class HMACEngineTest: public CppUnit::TestCase
{
public:
HMACEngineTest(const std::string& name);
~HMACEngineTest();
void testHMAC();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // HMACEngineTest_INCLUDED

View File

@@ -0,0 +1,222 @@
//
// HashMapTest.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "HashMapTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/HashMap.h"
#include "Poco/Exception.h"
#include <map>
using Poco::HashMap;
HashMapTest::HashMapTest(const std::string& name): CppUnit::TestCase(name)
{
}
HashMapTest::~HashMapTest()
{
}
void HashMapTest::testInsert()
{
const int N = 1000;
typedef HashMap<int, int> IntMap;
IntMap hm;
assertTrue (hm.empty());
for (int i = 0; i < N; ++i)
{
std::pair<IntMap::Iterator, bool> res = hm.insert(IntMap::ValueType(i, i*2));
assertTrue (res.first->first == i);
assertTrue (res.first->second == i*2);
assertTrue (res.second);
IntMap::Iterator it = hm.find(i);
assertTrue (it != hm.end());
assertTrue (it->first == i);
assertTrue (it->second == i*2);
assertTrue (hm.count(i) == 1);
assertTrue (hm.size() == i + 1);
}
assertTrue (!hm.empty());
for (int i = 0; i < N; ++i)
{
IntMap::Iterator it = hm.find(i);
assertTrue (it != hm.end());
assertTrue (it->first == i);
assertTrue (it->second == i*2);
}
for (int i = 0; i < N; ++i)
{
std::pair<IntMap::Iterator, bool> res = hm.insert(IntMap::ValueType(i, 0));
assertTrue (res.first->first == i);
assertTrue (res.first->second == i*2);
assertTrue (!res.second);
}
}
void HashMapTest::testErase()
{
const int N = 1000;
typedef HashMap<int, int> IntMap;
IntMap hm;
for (int i = 0; i < N; ++i)
{
hm.insert(IntMap::ValueType(i, i*2));
}
assertTrue (hm.size() == N);
for (int i = 0; i < N; i += 2)
{
hm.erase(i);
IntMap::Iterator it = hm.find(i);
assertTrue (it == hm.end());
}
assertTrue (hm.size() == N/2);
for (int i = 0; i < N; i += 2)
{
IntMap::Iterator it = hm.find(i);
assertTrue (it == hm.end());
}
for (int i = 1; i < N; i += 2)
{
IntMap::Iterator it = hm.find(i);
assertTrue (it != hm.end());
assertTrue (*it == i);
}
for (int i = 0; i < N; i += 2)
{
hm.insert(IntMap::ValueType(i, i*2));
}
for (int i = 0; i < N; ++i)
{
IntMap::Iterator it = hm.find(i);
assertTrue (it != hm.end());
assertTrue (it->first == i);
assertTrue (it->second == i*2);
}
}
void HashMapTest::testIterator()
{
const int N = 1000;
typedef HashMap<int, int> IntMap;
IntMap hm;
for (int i = 0; i < N; ++i)
{
hm.insert(IntMap::ValueType(i, i*2));
}
std::map<int, int> values;
IntMap::Iterator it; // do not initialize here to test proper behavior of uninitialized iterators
it = hm.begin();
while (it != hm.end())
{
assertTrue (values.find(it->first) == values.end());
values[it->first] = it->second;
++it;
}
assertTrue (values.size() == N);
}
void HashMapTest::testConstIterator()
{
const int N = 1000;
typedef HashMap<int, int> IntMap;
IntMap hm;
for (int i = 0; i < N; ++i)
{
hm.insert(IntMap::ValueType(i, i*2));
}
std::map<int, int> values;
IntMap::ConstIterator it = hm.begin();
while (it != hm.end())
{
assertTrue (values.find(it->first) == values.end());
values[it->first] = it->second;
++it;
}
assertTrue (values.size() == N);
}
void HashMapTest::testIndex()
{
typedef HashMap<int, int> IntMap;
IntMap hm;
hm[1] = 2;
hm[2] = 4;
hm[3] = 6;
assertTrue (hm.size() == 3);
assertTrue (hm[1] == 2);
assertTrue (hm[2] == 4);
assertTrue (hm[3] == 6);
try
{
const IntMap& im = hm;
int POCO_UNUSED x = im[4];
fail("no such key - must throw");
}
catch (Poco::NotFoundException&)
{
}
}
void HashMapTest::setUp()
{
}
void HashMapTest::tearDown()
{
}
CppUnit::Test* HashMapTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HashMapTest");
CppUnit_addTest(pSuite, HashMapTest, testInsert);
CppUnit_addTest(pSuite, HashMapTest, testErase);
CppUnit_addTest(pSuite, HashMapTest, testIterator);
CppUnit_addTest(pSuite, HashMapTest, testConstIterator);
CppUnit_addTest(pSuite, HashMapTest, testIndex);
return pSuite;
}

View File

@@ -0,0 +1,42 @@
//
// HashMapTest.h
//
// Definition of the HashMapTest class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef HashMapTest_INCLUDED
#define HashMapTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class HashMapTest: public CppUnit::TestCase
{
public:
HashMapTest(const std::string& name);
~HashMapTest();
void testInsert();
void testErase();
void testIterator();
void testConstIterator();
void testIndex();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // HashMapTest_INCLUDED

View File

@@ -0,0 +1,184 @@
//
// HashSetTest.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "HashSetTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/HashSet.h"
#include <set>
using Poco::Hash;
using Poco::HashSet;
HashSetTest::HashSetTest(const std::string& name): CppUnit::TestCase(name)
{
}
HashSetTest::~HashSetTest()
{
}
void HashSetTest::testInsert()
{
const int N = 1000;
HashSet<int, Hash<int> > hs;
assertTrue (hs.empty());
for (int i = 0; i < N; ++i)
{
std::pair<HashSet<int, Hash<int> >::Iterator, bool> res = hs.insert(i);
assertTrue (*res.first == i);
assertTrue (res.second);
HashSet<int, Hash<int> >::Iterator it = hs.find(i);
assertTrue (it != hs.end());
assertTrue (*it == i);
assertTrue (hs.size() == i + 1);
}
assertTrue (!hs.empty());
for (int i = 0; i < N; ++i)
{
HashSet<int, Hash<int> >::Iterator it = hs.find(i);
assertTrue (it != hs.end());
assertTrue (*it == i);
}
for (int i = 0; i < N; ++i)
{
std::pair<HashSet<int, Hash<int> >::Iterator, bool> res = hs.insert(i);
assertTrue (*res.first == i);
assertTrue (!res.second);
}
}
void HashSetTest::testErase()
{
const int N = 1000;
HashSet<int, Hash<int> > hs;
for (int i = 0; i < N; ++i)
{
hs.insert(i);
}
assertTrue (hs.size() == N);
for (int i = 0; i < N; i += 2)
{
hs.erase(i);
HashSet<int, Hash<int> >::Iterator it = hs.find(i);
assertTrue (it == hs.end());
}
assertTrue (hs.size() == N/2);
for (int i = 0; i < N; i += 2)
{
HashSet<int, Hash<int> >::Iterator it = hs.find(i);
assertTrue (it == hs.end());
}
for (int i = 1; i < N; i += 2)
{
HashSet<int, Hash<int> >::Iterator it = hs.find(i);
assertTrue (it != hs.end());
assertTrue (*it == i);
}
for (int i = 0; i < N; i += 2)
{
hs.insert(i);
}
for (int i = 0; i < N; ++i)
{
HashSet<int, Hash<int> >::Iterator it = hs.find(i);
assertTrue (it != hs.end());
assertTrue (*it == i);
}
}
void HashSetTest::testIterator()
{
const int N = 1000;
HashSet<int, Hash<int> > hs;
for (int i = 0; i < N; ++i)
{
hs.insert(i);
}
std::set<int> values;
HashSet<int, Hash<int> >::Iterator it = hs.begin();
while (it != hs.end())
{
assertTrue (values.find(*it) == values.end());
values.insert(*it);
++it;
}
assertTrue (values.size() == N);
}
void HashSetTest::testConstIterator()
{
const int N = 1000;
HashSet<int, Hash<int> > hs;
for (int i = 0; i < N; ++i)
{
hs.insert(i);
}
std::set<int> values;
HashSet<int, Hash<int> >::ConstIterator it = hs.begin();
while (it != hs.end())
{
assertTrue (values.find(*it) == values.end());
values.insert(*it);
++it;
}
assertTrue (values.size() == N);
}
void HashSetTest::setUp()
{
}
void HashSetTest::tearDown()
{
}
CppUnit::Test* HashSetTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HashSetTest");
CppUnit_addTest(pSuite, HashSetTest, testInsert);
CppUnit_addTest(pSuite, HashSetTest, testErase);
CppUnit_addTest(pSuite, HashSetTest, testIterator);
CppUnit_addTest(pSuite, HashSetTest, testConstIterator);
return pSuite;
}

View File

@@ -0,0 +1,41 @@
//
// HashSetTest.h
//
// Definition of the HashSetTest class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef HashSetTest_INCLUDED
#define HashSetTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class HashSetTest: public CppUnit::TestCase
{
public:
HashSetTest(const std::string& name);
~HashSetTest();
void testInsert();
void testErase();
void testIterator();
void testConstIterator();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // HashSetTest_INCLUDED

View File

@@ -0,0 +1,202 @@
//
// HashTableTest.cpp
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "HashTableTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/HashTable.h"
#include "Poco/NumberFormatter.h"
using namespace Poco;
HashTableTest::HashTableTest(const std::string& name): CppUnit::TestCase(name)
{
}
HashTableTest::~HashTableTest()
{
}
void HashTableTest::testInsert()
{
std::string s1("str1");
std::string s2("str2");
HashTable<std::string, int> hashTable;
assertTrue (!hashTable.exists(s1));
hashTable.insert(s1, 13);
assertTrue (hashTable.exists(s1));
assertTrue (hashTable.get(s1) == 13);
int retVal = 0;
assertTrue (hashTable.get(s1, retVal));
assertTrue (retVal == 13);
try
{
hashTable.insert(s1, 22);
failmsg ("duplicate insert must fail");
}
catch (Exception&){}
try
{
hashTable.get(s2);
failmsg ("getting a non inserted item must fail");
}
catch (Exception&){}
assertTrue (!hashTable.exists(s2));
hashTable.insert(s2, 13);
assertTrue (hashTable.exists(s2));
}
void HashTableTest::testUpdate()
{
// add code for second test here
std::string s1("str1");
std::string s2("str2");
HashTable<std::string, int> hashTable;
hashTable.insert(s1, 13);
hashTable.update(s1, 14);
assertTrue (hashTable.exists(s1));
assertTrue (hashTable.get(s1) == 14);
int retVal = 0;
assertTrue (hashTable.get(s1, retVal));
assertTrue (retVal == 14);
// updating a non existing item must work too
hashTable.update(s2, 15);
assertTrue (hashTable.get(s2) == 15);
}
void HashTableTest::testOverflow()
{
HashTable<std::string, int> hashTable(13);
for (int i = 0; i < 1024; ++i)
{
hashTable.insert(Poco::NumberFormatter::format(i), i*i);
}
for (int i = 0; i < 1024; ++i)
{
std::string tmp = Poco::NumberFormatter::format(i);
assertTrue (hashTable.exists(tmp));
assertTrue (hashTable.get(tmp) == i*i);
}
}
void HashTableTest::testSize()
{
HashTable<std::string, int> hashTable(13);
assertTrue (hashTable.size() == 0);
Poco::UInt32 POCO_UNUSED h1 = hashTable.insert("1", 1);
assertTrue (hashTable.size() == 1);
Poco::UInt32 POCO_UNUSED h2 = hashTable.update("2", 2);
assertTrue (hashTable.size() == 2);
hashTable.remove("1");
assertTrue (hashTable.size() == 1);
hashTable.remove("3");
assertTrue (hashTable.size() == 1);
hashTable.removeRaw("2", h2);
assertTrue (hashTable.size() == 0);
hashTable.insert("1", 1);
hashTable.insert("2", 2);
assertTrue (hashTable.size() == 2);
hashTable.clear();
assertTrue (hashTable.size() == 0);
}
void HashTableTest::testResize()
{
HashTable<std::string, int> hashTable(13);
assertTrue (hashTable.size() == 0);
hashTable.resize(19);
for (int i = 0; i < 1024; ++i)
{
hashTable.insert(Poco::NumberFormatter::format(i), i*i);
}
hashTable.resize(1009);
for (int i = 0; i < 1024; ++i)
{
std::string tmp = Poco::NumberFormatter::format(i);
assertTrue (hashTable.exists(tmp));
assertTrue (hashTable.get(tmp) == i*i);
}
}
void HashTableTest::testStatistic()
{
double relax = 0.001;
HashTable<std::string, int> hashTable(13);
assertTrue (hashTable.size() == 0);
HashStatistic stat1(hashTable.currentState());
assertTrue (stat1.avgEntriesPerHash() < relax && stat1.avgEntriesPerHash() > -relax);
assertTrue (stat1.maxPositionsOfTable() == 13);
assertTrue (stat1.maxEntriesPerHash() == 0);
hashTable.resize(19);
stat1 = hashTable.currentState(true);
assertTrue (stat1.avgEntriesPerHash() < relax && stat1.avgEntriesPerHash() > -relax);
assertTrue (stat1.maxPositionsOfTable() == 19);
assertTrue (stat1.maxEntriesPerHash() == 0);
assertTrue (stat1.detailedEntriesPerHash().size() == 19);
for (int i = 0; i < 1024; ++i)
{
hashTable.insert(Poco::NumberFormatter::format(i), i*i);
}
stat1 = hashTable.currentState(true);
double expAvg = 1024.0/ 19;
assertTrue (stat1.avgEntriesPerHash() < (expAvg + relax) && stat1.avgEntriesPerHash() > (expAvg - relax));
assertTrue (stat1.maxPositionsOfTable() == 19);
assertTrue (stat1.maxEntriesPerHash() > expAvg);
hashTable.resize(1009);
stat1 = hashTable.currentState(true);
expAvg = 1024.0/ 1009;
assertTrue (stat1.avgEntriesPerHash() < (expAvg + relax) && stat1.avgEntriesPerHash() > (expAvg - relax));
assertTrue (stat1.maxPositionsOfTable() == 1009);
assertTrue (stat1.maxEntriesPerHash() > expAvg);
}
void HashTableTest::setUp()
{
}
void HashTableTest::tearDown()
{
}
CppUnit::Test* HashTableTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HashTableTest");
CppUnit_addTest(pSuite, HashTableTest, testInsert);
CppUnit_addTest(pSuite, HashTableTest, testUpdate);
CppUnit_addTest(pSuite, HashTableTest, testOverflow);
CppUnit_addTest(pSuite, HashTableTest, testSize);
CppUnit_addTest(pSuite, HashTableTest, testResize);
CppUnit_addTest(pSuite, HashTableTest, testStatistic);
return pSuite;
}

View File

@@ -0,0 +1,43 @@
//
// HashTableTest.h
//
// Definition of the HashTableTest class.
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef HashTableTest_INCLUDED
#define HashTableTest_INCLUDED
#include "Poco/Foundation.h"
#include "CppUnit/TestCase.h"
class HashTableTest: public CppUnit::TestCase
{
public:
HashTableTest(const std::string& name);
~HashTableTest();
void testInsert();
void testOverflow();
void testUpdate();
void testSize();
void testResize();
void testStatistic();
void setUp();
void tearDown();
static CppUnit::Test* suite();
private:
};
#endif // HashTableTest_INCLUDED

View File

@@ -0,0 +1,30 @@
//
// HashingTestSuite.cpp
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "HashingTestSuite.h"
#include "HashTableTest.h"
#include "SimpleHashTableTest.h"
#include "LinearHashTableTest.h"
#include "HashSetTest.h"
#include "HashMapTest.h"
CppUnit::Test* HashingTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("HashingTestSuite");
pSuite->addTest(HashTableTest::suite());
pSuite->addTest(SimpleHashTableTest::suite());
pSuite->addTest(LinearHashTableTest::suite());
pSuite->addTest(HashSetTest::suite());
pSuite->addTest(HashMapTest::suite());
return pSuite;
}

Some files were not shown because too many files have changed in this diff Show More