to_string() is inline

warnigns fixed
use catch testing framework
This commit is contained in:
Marius Bancila 2018-05-15 09:41:49 +03:00
parent e1f1a1e59e
commit 13c6d59115
14 changed files with 14073 additions and 471 deletions

3
.gitignore vendored
View File

@ -30,3 +30,6 @@
*.exe
*.out
*.app
/build/.gitignore
build

View File

@ -2,32 +2,37 @@ cmake_minimum_required(VERSION 3.7.0)
project(test_uuid)
include_directories(${CMAKE_SOURCE_DIR}/include)
include_directories(${CMAKE_SOURCE_DIR}/catch)
file(GLOB headers ${CMAKE_SOURCE_DIR}/include/*.h)
file(GLOB SOURCES "test/*.cpp" "include/*.cpp")
add_executable(test_uuid ${SOURCES} ${headers})
if(WIN32)
message(status "Setting MSVC flags")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHc /std:c++latest")
add_definitions(-D_SCL_SECURE_NO_WARNINGS)
elseif(APPLE)
message(status "Setting Clang flags")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1z -fexceptions -g -Wall")
else()
include_directories(${LIBUUID_INCLUDE_DIR})
message(status "Setting GCC flags")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1z -fexceptions -g -Wall")
endif()
add_executable(test_uuid ${SOURCES} ${headers})
if(WIN32)
elseif(APPLE)
find_library(CFLIB CoreFoundation)
target_link_libraries(test_uuid ${CFLIB})
message(status "Setting Clang flags")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1z -fexceptions -g -Wall")
else()
find_package(Libuuid REQUIRED)
if (NOT LIBUUID_FOUND)
message(FATAL_ERROR
"You might need to run 'sudo apt-get install uuid-dev' or similar")
endif()
include_directories(${LIBUUID_INCLUDE_DIR})
target_link_libraries(test_uuid ${LIBUUID_LIBRARY})
message(status "Setting GCC flags")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1z -fexceptions -g -Wall")
endif()
message(status "** CMAKE_CXX_FLAGS: ${CMAKE_CXX_FLAGS}")

6
build/.gitignore vendored
View File

@ -1,6 +0,0 @@
#ignore all
/*
# keep these files
!.gitignore
!readme.txt

View File

@ -1,12 +0,0 @@
Create a project from this folder by running the command:
Windows
cmake -G "Visual Studio 15 2017" [arch] ..
where arch is an optional parameter and can be Win64 or ARM. Without one specified, x86 target
Mac
cmake -G Xcode ..
If you don't have CMake installed you can get it from https://cmake.org/

13050
catch/catch.hpp Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,62 @@
/*
* Created by Justin R. Wilson on 2/19/2017.
* Copyright 2017 Justin R. Wilson. All rights reserved.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED
// Don't #include any Catch headers here - we can assume they are already
// included before this header.
// This is not good practice in general but is necessary in this case so this
// file can be distributed as a single header that works with the main
// Catch single header.
namespace Catch {
struct AutomakeReporter : StreamingReporterBase<AutomakeReporter> {
AutomakeReporter( ReporterConfig const& _config )
: StreamingReporterBase( _config )
{}
~AutomakeReporter() override;
static std::string getDescription() {
return "Reports test results in the format of Automake .trs files";
}
void assertionStarting( AssertionInfo const& ) override {}
bool assertionEnded( AssertionStats const& /*_assertionStats*/ ) override { return true; }
void testCaseEnded( TestCaseStats const& _testCaseStats ) override {
// Possible values to emit are PASS, XFAIL, SKIP, FAIL, XPASS and ERROR.
stream << ":test-result: ";
if (_testCaseStats.totals.assertions.allPassed()) {
stream << "PASS";
} else if (_testCaseStats.totals.assertions.allOk()) {
stream << "XFAIL";
} else {
stream << "FAIL";
}
stream << ' ' << _testCaseStats.testInfo.name << '\n';
StreamingReporterBase::testCaseEnded( _testCaseStats );
}
void skipTest( TestCaseInfo const& testInfo ) override {
stream << ":test-result: SKIP " << testInfo.name << '\n';
}
};
#ifdef CATCH_IMPL
AutomakeReporter::~AutomakeReporter() {}
#endif
CATCH_REGISTER_REPORTER( "automake", AutomakeReporter)
} // end namespace Catch
#endif // TWOBLUECUBES_CATCH_REPORTER_AUTOMAKE_HPP_INCLUDED

View File

@ -0,0 +1,255 @@
/*
* Created by Colton Wolkins on 2015-08-15.
* Copyright 2015 Martin Moene. All rights reserved.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED
// Don't #include any Catch headers here - we can assume they are already
// included before this header.
// This is not good practice in general but is necessary in this case so this
// file can be distributed as a single header that works with the main
// Catch single header.
#include <algorithm>
namespace Catch {
struct TAPReporter : StreamingReporterBase<TAPReporter> {
using StreamingReporterBase::StreamingReporterBase;
~TAPReporter() override;
static std::string getDescription() {
return "Reports test results in TAP format, suitable for test harnesses";
}
ReporterPreferences getPreferences() const override {
ReporterPreferences prefs;
prefs.shouldRedirectStdOut = false;
return prefs;
}
void noMatchingTestCases( std::string const& spec ) override {
stream << "# No test cases matched '" << spec << "'" << std::endl;
}
void assertionStarting( AssertionInfo const& ) override {}
bool assertionEnded( AssertionStats const& _assertionStats ) override {
++counter;
AssertionPrinter printer( stream, _assertionStats, counter );
printer.print();
stream << " # " << currentTestCaseInfo->name ;
stream << std::endl;
return true;
}
void testRunEnded( TestRunStats const& _testRunStats ) override {
printTotals( _testRunStats.totals );
stream << "\n" << std::endl;
StreamingReporterBase::testRunEnded( _testRunStats );
}
private:
std::size_t counter = 0;
class AssertionPrinter {
public:
AssertionPrinter& operator= ( AssertionPrinter const& ) = delete;
AssertionPrinter( AssertionPrinter const& ) = delete;
AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, std::size_t _counter )
: stream( _stream )
, result( _stats.assertionResult )
, messages( _stats.infoMessages )
, itMessage( _stats.infoMessages.begin() )
, printInfoMessages( true )
, counter(_counter)
{}
void print() {
itMessage = messages.begin();
switch( result.getResultType() ) {
case ResultWas::Ok:
printResultType( passedString() );
printOriginalExpression();
printReconstructedExpression();
if ( ! result.hasExpression() )
printRemainingMessages( Colour::None );
else
printRemainingMessages();
break;
case ResultWas::ExpressionFailed:
if (result.isOk()) {
printResultType(passedString());
} else {
printResultType(failedString());
}
printOriginalExpression();
printReconstructedExpression();
if (result.isOk()) {
printIssue(" # TODO");
}
printRemainingMessages();
break;
case ResultWas::ThrewException:
printResultType( failedString() );
printIssue( "unexpected exception with message:" );
printMessage();
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::FatalErrorCondition:
printResultType( failedString() );
printIssue( "fatal error condition with message:" );
printMessage();
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::DidntThrowException:
printResultType( failedString() );
printIssue( "expected exception, got none" );
printExpressionWas();
printRemainingMessages();
break;
case ResultWas::Info:
printResultType( "info" );
printMessage();
printRemainingMessages();
break;
case ResultWas::Warning:
printResultType( "warning" );
printMessage();
printRemainingMessages();
break;
case ResultWas::ExplicitFailure:
printResultType( failedString() );
printIssue( "explicitly" );
printRemainingMessages( Colour::None );
break;
// These cases are here to prevent compiler warnings
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
printResultType( "** internal error **" );
break;
}
}
private:
static Colour::Code dimColour() { return Colour::FileName; }
static const char* failedString() { return "not ok"; }
static const char* passedString() { return "ok"; }
void printSourceInfo() const {
Colour colourGuard( dimColour() );
stream << result.getSourceInfo() << ":";
}
void printResultType( std::string const& passOrFail ) const {
if( !passOrFail.empty() ) {
stream << passOrFail << ' ' << counter << " -";
}
}
void printIssue( std::string const& issue ) const {
stream << " " << issue;
}
void printExpressionWas() {
if( result.hasExpression() ) {
stream << ";";
{
Colour colour( dimColour() );
stream << " expression was:";
}
printOriginalExpression();
}
}
void printOriginalExpression() const {
if( result.hasExpression() ) {
stream << " " << result.getExpression();
}
}
void printReconstructedExpression() const {
if( result.hasExpandedExpression() ) {
{
Colour colour( dimColour() );
stream << " for: ";
}
std::string expr = result.getExpandedExpression();
std::replace( expr.begin(), expr.end(), '\n', ' ');
stream << expr;
}
}
void printMessage() {
if ( itMessage != messages.end() ) {
stream << " '" << itMessage->message << "'";
++itMessage;
}
}
void printRemainingMessages( Colour::Code colour = dimColour() ) {
if (itMessage == messages.end()) {
return;
}
// using messages.end() directly (or auto) yields compilation error:
std::vector<MessageInfo>::const_iterator itEnd = messages.end();
const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );
{
Colour colourGuard( colour );
stream << " with " << pluralise( N, "message" ) << ":";
}
for(; itMessage != itEnd; ) {
// If this assertion is a warning ignore any INFO messages
if( printInfoMessages || itMessage->type != ResultWas::Info ) {
stream << " '" << itMessage->message << "'";
if ( ++itMessage != itEnd ) {
Colour colourGuard( dimColour() );
stream << " and";
}
}
}
}
private:
std::ostream& stream;
AssertionResult const& result;
std::vector<MessageInfo> messages;
std::vector<MessageInfo>::const_iterator itMessage;
bool printInfoMessages;
std::size_t counter;
};
void printTotals( const Totals& totals ) const {
if( totals.testCases.total() == 0 ) {
stream << "1..0 # Skipped: No tests ran.";
} else {
stream << "1.." << counter;
}
}
};
#ifdef CATCH_IMPL
TAPReporter::~TAPReporter() {}
#endif
CATCH_REGISTER_REPORTER( "tap", TAPReporter )
} // end namespace Catch
#endif // TWOBLUECUBES_CATCH_REPORTER_TAP_HPP_INCLUDED

View File

@ -0,0 +1,220 @@
/*
* Created by Phil Nash on 19th December 2014
* Copyright 2014 Two Blue Cubes Ltd. All rights reserved.
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED
#define TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED
// Don't #include any Catch headers here - we can assume they are already
// included before this header.
// This is not good practice in general but is necessary in this case so this
// file can be distributed as a single header that works with the main
// Catch single header.
#include <cstring>
#ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wpadded"
#endif
namespace Catch {
struct TeamCityReporter : StreamingReporterBase<TeamCityReporter> {
TeamCityReporter( ReporterConfig const& _config )
: StreamingReporterBase( _config )
{
m_reporterPrefs.shouldRedirectStdOut = true;
}
static std::string escape( std::string const& str ) {
std::string escaped = str;
replaceInPlace( escaped, "|", "||" );
replaceInPlace( escaped, "'", "|'" );
replaceInPlace( escaped, "\n", "|n" );
replaceInPlace( escaped, "\r", "|r" );
replaceInPlace( escaped, "[", "|[" );
replaceInPlace( escaped, "]", "|]" );
return escaped;
}
~TeamCityReporter() override;
static std::string getDescription() {
return "Reports test results as TeamCity service messages";
}
void skipTest( TestCaseInfo const& /* testInfo */ ) override {
}
void noMatchingTestCases( std::string const& /* spec */ ) override {}
void testGroupStarting( GroupInfo const& groupInfo ) override {
StreamingReporterBase::testGroupStarting( groupInfo );
stream << "##teamcity[testSuiteStarted name='"
<< escape( groupInfo.name ) << "']\n";
}
void testGroupEnded( TestGroupStats const& testGroupStats ) override {
StreamingReporterBase::testGroupEnded( testGroupStats );
stream << "##teamcity[testSuiteFinished name='"
<< escape( testGroupStats.groupInfo.name ) << "']\n";
}
void assertionStarting( AssertionInfo const& ) override {}
bool assertionEnded( AssertionStats const& assertionStats ) override {
AssertionResult const& result = assertionStats.assertionResult;
if( !result.isOk() ) {
ReusableStringStream msg;
if( !m_headerPrintedForThisSection )
printSectionHeader( msg.get() );
m_headerPrintedForThisSection = true;
msg << result.getSourceInfo() << "\n";
switch( result.getResultType() ) {
case ResultWas::ExpressionFailed:
msg << "expression failed";
break;
case ResultWas::ThrewException:
msg << "unexpected exception";
break;
case ResultWas::FatalErrorCondition:
msg << "fatal error condition";
break;
case ResultWas::DidntThrowException:
msg << "no exception was thrown where one was expected";
break;
case ResultWas::ExplicitFailure:
msg << "explicit failure";
break;
// We shouldn't get here because of the isOk() test
case ResultWas::Ok:
case ResultWas::Info:
case ResultWas::Warning:
throw std::domain_error( "Internal error in TeamCity reporter" );
// These cases are here to prevent compiler warnings
case ResultWas::Unknown:
case ResultWas::FailureBit:
case ResultWas::Exception:
throw std::domain_error( "Not implemented" );
}
if( assertionStats.infoMessages.size() == 1 )
msg << " with message:";
if( assertionStats.infoMessages.size() > 1 )
msg << " with messages:";
for( auto const& messageInfo : assertionStats.infoMessages )
msg << "\n \"" << messageInfo.message << "\"";
if( result.hasExpression() ) {
msg <<
"\n " << result.getExpressionInMacro() << "\n"
"with expansion:\n" <<
" " << result.getExpandedExpression() << "\n";
}
if( currentTestCaseInfo->okToFail() ) {
msg << "- failure ignore as test marked as 'ok to fail'\n";
stream << "##teamcity[testIgnored"
<< " name='" << escape( currentTestCaseInfo->name )<< "'"
<< " message='" << escape( msg.str() ) << "'"
<< "]\n";
}
else {
stream << "##teamcity[testFailed"
<< " name='" << escape( currentTestCaseInfo->name )<< "'"
<< " message='" << escape( msg.str() ) << "'"
<< "]\n";
}
}
stream.flush();
return true;
}
void sectionStarting( SectionInfo const& sectionInfo ) override {
m_headerPrintedForThisSection = false;
StreamingReporterBase::sectionStarting( sectionInfo );
}
void testCaseStarting( TestCaseInfo const& testInfo ) override {
m_testTimer.start();
StreamingReporterBase::testCaseStarting( testInfo );
stream << "##teamcity[testStarted name='"
<< escape( testInfo.name ) << "']\n";
stream.flush();
}
void testCaseEnded( TestCaseStats const& testCaseStats ) override {
StreamingReporterBase::testCaseEnded( testCaseStats );
if( !testCaseStats.stdOut.empty() )
stream << "##teamcity[testStdOut name='"
<< escape( testCaseStats.testInfo.name )
<< "' out='" << escape( testCaseStats.stdOut ) << "']\n";
if( !testCaseStats.stdErr.empty() )
stream << "##teamcity[testStdErr name='"
<< escape( testCaseStats.testInfo.name )
<< "' out='" << escape( testCaseStats.stdErr ) << "']\n";
stream << "##teamcity[testFinished name='"
<< escape( testCaseStats.testInfo.name ) << "' duration='"
<< m_testTimer.getElapsedMilliseconds() << "']\n";
stream.flush();
}
private:
void printSectionHeader( std::ostream& os ) {
assert( !m_sectionStack.empty() );
if( m_sectionStack.size() > 1 ) {
os << getLineOfChars<'-'>() << "\n";
std::vector<SectionInfo>::const_iterator
it = m_sectionStack.begin()+1, // Skip first section (test case)
itEnd = m_sectionStack.end();
for( ; it != itEnd; ++it )
printHeaderString( os, it->name );
os << getLineOfChars<'-'>() << "\n";
}
SourceLineInfo lineInfo = m_sectionStack.front().lineInfo;
if( !lineInfo.empty() )
os << lineInfo << "\n";
os << getLineOfChars<'.'>() << "\n\n";
}
// if string has a : in first line will set indent to follow it on
// subsequent lines
static void printHeaderString( std::ostream& os, std::string const& _string, std::size_t indent = 0 ) {
std::size_t i = _string.find( ": " );
if( i != std::string::npos )
i+=2;
else
i = 0;
os << Column( _string )
.indent( indent+i)
.initialIndent( indent ) << "\n";
}
private:
bool m_headerPrintedForThisSection = false;
Timer m_testTimer;
};
#ifdef CATCH_IMPL
TeamCityReporter::~TeamCityReporter() {}
#endif
CATCH_REGISTER_REPORTER( "teamcity", TeamCityReporter )
} // end namespace Catch
#ifdef __clang__
# pragma clang diagnostic pop
#endif
#endif // TWOBLUECUBES_CATCH_REPORTER_TEAMCITY_HPP_INCLUDED

40
how_to_build.md Normal file
View File

@ -0,0 +1,40 @@
# How to build
You can create projects to build the tests for the uuid library using CMake.
If you don't have CMake installed you can get it from https://cmake.org/.
## Windows
Do the Following:
* Create a folder called **build**
```
mkdir build
cd build
```
* Run the following CMake command from the **build** folder to generate projects to target the **x86** platform.
```
cmake -G "Visual Studio 15 2017" ..
```
To generate projects to target **x64** use the generator **"Visual Studio 15 2017 Win64"**.
To generate projects to target **ARM** use the generator **"Visual Studio 15 2017 ARM"**.
## Mac
Do the Following:
* Create a folder called **build**
```
mkdir build
cd build
```
* Run the following CMake command from the **build** folder to generate projects to target the **x86** platform.
```
cmake -G Xcode ..
```

View File

@ -420,8 +420,9 @@ namespace uuids
self_type & operator+=(difference_type const offset)
{
if (index + offset < 0 || index + offset > uuid::state_size)
throw std::out_of_range("Iterator cannot be incremented past the end of the data.");
if (static_cast<difference_type>(index) + offset < 0 ||
static_cast<difference_type>(index) + offset > uuid::state_size)
throw std::out_of_range("Iterator cannot be incremented outside data bounds.");
index += offset;
return *this;
@ -564,8 +565,9 @@ namespace uuids
self_type & operator+=(difference_type const offset)
{
if (index + offset < 0 || index + offset > uuid::state_size)
throw std::out_of_range("Iterator cannot be incremented past the end of the data.");
if (static_cast<difference_type>(index) + offset < 0 ||
static_cast<difference_type>(index) + offset > uuid::state_size)
throw std::out_of_range("Iterator cannot be incremented outside data bounds.");
index += offset;
return *this;
@ -750,14 +752,14 @@ namespace uuids
<< std::setw(2) << (int)id.data[15];
}
std::string to_string(uuid const & id)
inline std::string to_string(uuid const & id)
{
std::stringstream sstr;
sstr << id;
return sstr.str();
}
std::wstring to_wstring(uuid const & id)
inline std::wstring to_wstring(uuid const & id)
{
std::wstringstream sstr;
sstr << id;

3
test/main.cpp Normal file
View File

@ -0,0 +1,3 @@
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

View File

@ -1,438 +0,0 @@
#include "../include/uuid.h"
#include <assert.h>
#include <iostream>
#include <set>
#include <unordered_set>
#include <random>
#include <vector>
int main()
{
using namespace uuids;
{
std::cout << "Test default constructor" << std::endl;
uuid empty;
assert(empty.is_nil());
assert(empty.size() == 16);
}
{
std::cout << "Test string_view constructor" << std::endl;
using namespace std::string_literals;
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e43"s;
uuid guid(str);
assert(uuids::to_string(guid) == str);
}
{
uuid guid("47183823-2574-4bfd-b411-99ed177d3e43");
assert(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
assert(uuids::to_wstring(guid) == L"47183823-2574-4bfd-b411-99ed177d3e43");
}
}
{
std::cout << "Test wstring_view constructor" << std::endl;
using namespace std::string_literals;
auto str = L"47183823-2574-4bfd-b411-99ed177d3e43"s;
uuid guid(str);
assert(uuids::to_wstring(guid) == str);
}
{
std::cout << "Test iterators constructor" << std::endl;
using namespace std::string_literals;
{
std::array<uuids::uuid::value_type, 16> arr{ {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43} };
uuid guid(std::begin(arr), std::end(arr));
assert(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43"s);
}
{
uuids::uuid::value_type arr[16] = {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43 };
uuid guid(std::begin(arr), std::end(arr));
assert(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43"s);
}
}
{
std::cout << "Test equality" << std::endl;
uuid empty;
uuid guid = uuids::uuid_random_generator{}();
assert(empty == empty);
assert(guid == guid);
assert(empty != guid);
}
{
std::cout << "Test comparison" << std::endl;
auto empty = uuid{};
uuids::uuid_random_generator gen;
auto id = gen();
assert(empty < id);
std::set<uuids::uuid> ids{
uuid{},
gen(),
gen(),
gen(),
gen()
};
assert(ids.size() == 5);
assert(ids.find(uuid{}) != ids.end());
}
{
std::cout << "Test hashing" << std::endl;
using namespace std::string_literals;
auto str = "47183823-2574-4bfd-b411-99ed177d3e43"s;
auto guid = uuid{ str };
auto h1 = std::hash<std::string>{};
auto h2 = std::hash<uuid>{};
assert(h1(str) == h2(guid));
uuids::uuid_random_generator gen;
std::unordered_set<uuids::uuid> ids{
uuid{},
gen(),
gen(),
gen(),
gen()
};
assert(ids.size() == 5);
assert(ids.find(uuid{}) != ids.end());
}
{
std::cout << "Test swap" << std::endl;
uuid empty;
uuid guid = uuids::uuid_random_generator{}();
assert(empty.is_nil());
assert(!guid.is_nil());
std::swap(empty, guid);
assert(!empty.is_nil());
assert(guid.is_nil());
empty.swap(guid);
assert(empty.is_nil());
assert(!guid.is_nil());
}
{
std::cout << "Test string conversion" << std::endl;
uuid empty;
assert(uuids::to_string(empty) == "00000000-0000-0000-0000-000000000000");
assert(uuids::to_wstring(empty) == L"00000000-0000-0000-0000-000000000000");
}
{
std::cout << "Test iterators" << std::endl;
std::array<uuids::uuid::value_type, 16> arr{{
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43
}};
{
uuid guid;
assert(guid.is_nil());
std::copy(std::cbegin(arr), std::cend(arr), std::begin(guid));
assert(!guid.is_nil());
assert(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
size_t i = 0;
for (auto const & b : guid)
{
assert(arr[i++] == b);
}
}
{
const uuid guid("47183823-2574-4bfd-b411-99ed177d3e43");
assert(!guid.is_nil());
assert(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
size_t i = 0;
for (auto const & b : guid)
{
assert(arr[i++] == b);
}
}
}
{
std::cout << "Test constexpr" << std::endl;
constexpr uuid empty;
constexpr bool isnil = empty.is_nil();
constexpr size_t size = empty.size();
constexpr uuid_variant variant = empty.variant();
constexpr uuid_version version = empty.version();
}
{
std::cout << "Test default generator" << std::endl;
uuid const guid = uuids::uuid_random_generator{}();
assert(!guid.is_nil());
assert(guid.size() == 16);
assert(guid.version() == uuids::uuid_version::random_number_based);
assert(guid.variant() == uuids::uuid_variant::rfc);
}
{
std::cout << "Test random generator (default ctor)" << std::endl;
uuids::uuid_random_generator dgen;
auto id1 = dgen();
assert(!id1.is_nil());
assert(id1.size() == 16);
assert(id1.version() == uuids::uuid_version::random_number_based);
assert(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
assert(!id2.is_nil());
assert(id2.size() == 16);
assert(id2.version() == uuids::uuid_version::random_number_based);
assert(id2.variant() == uuids::uuid_variant::rfc);
assert(id1 != id2);
}
{
std::cout << "Test random generator (conversion ctor w/ ptr)" << std::endl;
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::mt19937 generator(seq);
uuids::uuid_random_generator dgen(&generator);
auto id1 = dgen();
assert(!id1.is_nil());
assert(id1.size() == 16);
assert(id1.version() == uuids::uuid_version::random_number_based);
assert(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
assert(!id2.is_nil());
assert(id2.size() == 16);
assert(id2.version() == uuids::uuid_version::random_number_based);
assert(id2.variant() == uuids::uuid_variant::rfc);
assert(id1 != id2);
}
{
std::cout << "Test random generator (conversion ctor w/ ptr)" << std::endl;
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
auto generator = std::make_unique<std::mt19937>(seq);
uuids::uuid_random_generator dgen(generator.get());
auto id1 = dgen();
assert(!id1.is_nil());
assert(id1.size() == 16);
assert(id1.version() == uuids::uuid_version::random_number_based);
assert(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
assert(!id1.is_nil());
assert(id2.size() == 16);
assert(id2.version() == uuids::uuid_version::random_number_based);
assert(id2.variant() == uuids::uuid_variant::rfc);
assert(id1 != id2);
}
{
std::cout << "Test random generator (conversion ctor w/ ref)" << std::endl;
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::mt19937 generator(seq);
uuids::uuid_random_generator dgen(generator);
auto id1 = dgen();
assert(!id1.is_nil());
assert(id1.size() == 16);
assert(id1.version() == uuids::uuid_version::random_number_based);
assert(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
assert(!id2.is_nil());
assert(id2.size() == 16);
assert(id2.version() == uuids::uuid_version::random_number_based);
assert(id2.variant() == uuids::uuid_variant::rfc);
assert(id1 != id2);
}
{
std::cout << "Test basic random generator (default ctor) w/ ranlux48_base" << std::endl;
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen;
auto id1 = dgen();
assert(!id1.is_nil());
assert(id1.size() == 16);
assert(id1.version() == uuids::uuid_version::random_number_based);
assert(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
assert(!id1.is_nil());
assert(id2.size() == 16);
assert(id2.version() == uuids::uuid_version::random_number_based);
assert(id2.variant() == uuids::uuid_variant::rfc);
assert(id1 != id2);
}
{
std::cout << "Test basic random generator (conversion ctor w/ ptr) w/ ranlux48_base" << std::endl;
std::random_device rd;
std::ranlux48_base generator(rd());
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen(&generator);
auto id1 = dgen();
assert(!id1.is_nil());
assert(id1.size() == 16);
assert(id1.version() == uuids::uuid_version::random_number_based);
assert(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
assert(!id2.is_nil());
assert(id2.size() == 16);
assert(id2.version() == uuids::uuid_version::random_number_based);
assert(id2.variant() == uuids::uuid_variant::rfc);
assert(id1 != id2);
}
{
std::cout << "Test basic random generator (conversion ctor w/ ptr) w/ ranlux48_base" << std::endl;
std::random_device rd;
auto generator = std::make_unique<std::ranlux48_base>(rd());
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen(generator.get());
auto id1 = dgen();
assert(!id1.is_nil());
assert(id1.size() == 16);
assert(id1.version() == uuids::uuid_version::random_number_based);
assert(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
assert(!id2.is_nil());
assert(id2.size() == 16);
assert(id2.version() == uuids::uuid_version::random_number_based);
assert(id2.variant() == uuids::uuid_variant::rfc);
assert(id1 != id2);
}
{
std::cout << "Test basic random generator (conversion ctor w/ ref) w/ ranlux48_base" << std::endl;
std::random_device rd;
std::ranlux48_base generator(rd());
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen(generator);
auto id1 = dgen();
assert(!id1.is_nil());
assert(id1.size() == 16);
assert(id1.version() == uuids::uuid_version::random_number_based);
assert(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
assert(!id2.is_nil());
assert(id2.size() == 16);
assert(id2.version() == uuids::uuid_version::random_number_based);
assert(id2.variant() == uuids::uuid_variant::rfc);
assert(id1 != id2);
}
{
std::cout << "Test name generator" << std::endl;
uuids::uuid_name_generator dgen(uuids::uuid{"47183823-2574-4bfd-b411-99ed177d3e43"});
auto id1 = dgen("john");
assert(!id1.is_nil());
assert(id1.size() == 16);
assert(id1.version() == uuids::uuid_version::name_based_sha1);
assert(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen("jane");
assert(!id2.is_nil());
assert(id2.size() == 16);
assert(id2.version() == uuids::uuid_version::name_based_sha1);
assert(id2.variant() == uuids::uuid_variant::rfc);
auto id3 = dgen("jane");
assert(!id3.is_nil());
assert(id3.size() == 16);
assert(id3.version() == uuids::uuid_version::name_based_sha1);
assert(id3.variant() == uuids::uuid_variant::rfc);
auto id4 = dgen(L"jane");
assert(!id4.is_nil());
assert(id4.size() == 16);
assert(id4.version() == uuids::uuid_version::name_based_sha1);
assert(id4.variant() == uuids::uuid_variant::rfc);
assert(id1 != id2);
assert(id2 == id3);
assert(id3 != id4);
}
std::cout << "ALL PASSED" << std::endl;
return 0;
}

221
test/test_generators.cpp Normal file
View File

@ -0,0 +1,221 @@
#include "uuid.h"
#include "catch.hpp"
#include <set>
#include <unordered_set>
#include <random>
#include <vector>
using namespace uuids;
TEST_CASE("Test default generator", "[gen][rand]")
{
uuid const guid = uuids::uuid_random_generator{}();
REQUIRE(!guid.is_nil());
REQUIRE(guid.size() == 16);
REQUIRE(guid.version() == uuids::uuid_version::random_number_based);
REQUIRE(guid.variant() == uuids::uuid_variant::rfc);
}
TEST_CASE("Test random generator (default ctor)", "[gen][rand]")
{
uuids::uuid_random_generator dgen;
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.size() == 16);
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.size() == 16);
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test random generator (conversion ctor w/ smart ptr)", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::mt19937 generator(seq);
uuids::uuid_random_generator dgen(&generator);
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.size() == 16);
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.size() == 16);
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test random generator (conversion ctor w/ ptr)", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
auto generator = std::make_unique<std::mt19937>(seq);
uuids::uuid_random_generator dgen(generator.get());
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.size() == 16);
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id2.size() == 16);
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test random generator (conversion ctor w/ ref)", "[gen][rand]")
{
std::random_device rd;
auto seed_data = std::array<int, std::mt19937::state_size> {};
std::generate(std::begin(seed_data), std::end(seed_data), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
std::mt19937 generator(seq);
uuids::uuid_random_generator dgen(generator);
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.size() == 16);
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.size() == 16);
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test basic random generator (default ctor) w/ ranlux48_base", "[gen][rand]")
{
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen;
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.size() == 16);
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id2.size() == 16);
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test basic random generator (conversion ctor w/ ptr) w/ ranlux48_base", "[gen][rand]")
{
std::random_device rd;
std::ranlux48_base generator(rd());
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen(&generator);
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.size() == 16);
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.size() == 16);
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test basic random generator (conversion ctor w/ smart ptr) w/ ranlux48_base", "[gen][rand]")
{
std::random_device rd;
auto generator = std::make_unique<std::ranlux48_base>(rd());
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen(generator.get());
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.size() == 16);
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.size() == 16);
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test basic random generator (conversion ctor w/ ref) w/ ranlux48_base", "[gen][rand]")
{
std::random_device rd;
std::ranlux48_base generator(rd());
uuids::basic_uuid_random_generator<std::ranlux48_base> dgen(generator);
auto id1 = dgen();
REQUIRE(!id1.is_nil());
REQUIRE(id1.size() == 16);
REQUIRE(id1.version() == uuids::uuid_version::random_number_based);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen();
REQUIRE(!id2.is_nil());
REQUIRE(id2.size() == 16);
REQUIRE(id2.version() == uuids::uuid_version::random_number_based);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
}
TEST_CASE("Test name generator", "[gen][name]")
{
uuids::uuid_name_generator dgen(uuids::uuid{ "47183823-2574-4bfd-b411-99ed177d3e43" });
auto id1 = dgen("john");
REQUIRE(!id1.is_nil());
REQUIRE(id1.size() == 16);
REQUIRE(id1.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id1.variant() == uuids::uuid_variant::rfc);
auto id2 = dgen("jane");
REQUIRE(!id2.is_nil());
REQUIRE(id2.size() == 16);
REQUIRE(id2.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id2.variant() == uuids::uuid_variant::rfc);
auto id3 = dgen("jane");
REQUIRE(!id3.is_nil());
REQUIRE(id3.size() == 16);
REQUIRE(id3.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id3.variant() == uuids::uuid_variant::rfc);
auto id4 = dgen(L"jane");
REQUIRE(!id4.is_nil());
REQUIRE(id4.size() == 16);
REQUIRE(id4.version() == uuids::uuid_version::name_based_sha1);
REQUIRE(id4.variant() == uuids::uuid_variant::rfc);
REQUIRE(id1 != id2);
REQUIRE(id2 == id3);
REQUIRE(id3 != id4);
}

197
test/test_uuid.cpp Normal file
View File

@ -0,0 +1,197 @@
#include "uuid.h"
#include "catch.hpp"
#include <set>
#include <unordered_set>
#include <vector>
using namespace uuids;
TEST_CASE("Test default constructor", "[ctors]")
{
uuid empty;
REQUIRE(empty.is_nil());
REQUIRE(empty.size() == 16);
}
TEST_CASE("Test string_view constructor", "[ctors]")
{
using namespace std::string_literals;
{
auto str = "47183823-2574-4bfd-b411-99ed177d3e43"s;
uuid guid(str);
REQUIRE(uuids::to_string(guid) == str);
}
{
uuid guid("47183823-2574-4bfd-b411-99ed177d3e43");
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
REQUIRE(uuids::to_wstring(guid) == L"47183823-2574-4bfd-b411-99ed177d3e43");
}
}
TEST_CASE("Test wstring_view constructor", "[ctors]")
{
using namespace std::string_literals;
auto str = L"47183823-2574-4bfd-b411-99ed177d3e43"s;
uuid guid(str);
REQUIRE(uuids::to_wstring(guid) == str);
}
TEST_CASE("Test iterators constructor", "[ctors]")
{
using namespace std::string_literals;
{
std::array<uuids::uuid::value_type, 16> arr{ {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43 } };
uuid guid(std::begin(arr), std::end(arr));
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43"s);
}
{
uuids::uuid::value_type arr[16] = {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43 };
uuid guid(std::begin(arr), std::end(arr));
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43"s);
}
}
TEST_CASE("Test equality", "[operators]")
{
uuid empty;
uuid guid = uuids::uuid_random_generator{}();
REQUIRE(empty == empty);
REQUIRE(guid == guid);
REQUIRE(empty != guid);
}
TEST_CASE("Test comparison", "[operators]")
{
auto empty = uuid{};
uuids::uuid_random_generator gen;
auto id = gen();
REQUIRE(empty < id);
std::set<uuids::uuid> ids{
uuid{},
gen(),
gen(),
gen(),
gen()
};
REQUIRE(ids.size() == 5);
REQUIRE(ids.find(uuid{}) != ids.end());
}
TEST_CASE("Test hashing", "[ops]")
{
using namespace std::string_literals;
auto str = "47183823-2574-4bfd-b411-99ed177d3e43"s;
auto guid = uuid{ str };
auto h1 = std::hash<std::string>{};
auto h2 = std::hash<uuid>{};
REQUIRE(h1(str) == h2(guid));
uuids::uuid_random_generator gen;
std::unordered_set<uuids::uuid> ids{
uuid{},
gen(),
gen(),
gen(),
gen()
};
REQUIRE(ids.size() == 5);
REQUIRE(ids.find(uuid{}) != ids.end());
}
TEST_CASE("Test swap", "[ops]")
{
uuid empty;
uuid guid = uuids::uuid_random_generator{}();
REQUIRE(empty.is_nil());
REQUIRE(!guid.is_nil());
std::swap(empty, guid);
REQUIRE(!empty.is_nil());
REQUIRE(guid.is_nil());
empty.swap(guid);
REQUIRE(empty.is_nil());
REQUIRE(!guid.is_nil());
}
TEST_CASE("Test string conversion", "[ops]")
{
uuid empty;
REQUIRE(uuids::to_string(empty) == "00000000-0000-0000-0000-000000000000");
REQUIRE(uuids::to_wstring(empty) == L"00000000-0000-0000-0000-000000000000");
}
TEST_CASE("Test iterators", "[iter]")
{
std::array<uuids::uuid::value_type, 16> arr{ {
0x47, 0x18, 0x38, 0x23,
0x25, 0x74,
0x4b, 0xfd,
0xb4, 0x11,
0x99, 0xed, 0x17, 0x7d, 0x3e, 0x43
} };
{
uuid guid;
REQUIRE(guid.is_nil());
std::copy(std::cbegin(arr), std::cend(arr), std::begin(guid));
REQUIRE(!guid.is_nil());
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
size_t i = 0;
for (auto const & b : guid)
{
REQUIRE(arr[i++] == b);
}
}
{
const uuid guid("47183823-2574-4bfd-b411-99ed177d3e43");
REQUIRE(!guid.is_nil());
REQUIRE(uuids::to_string(guid) == "47183823-2574-4bfd-b411-99ed177d3e43");
size_t i = 0;
for (auto const & b : guid)
{
REQUIRE(arr[i++] == b);
}
}
}
TEST_CASE("Test constexpr", "[const]")
{
constexpr uuid empty;
constexpr bool isnil = empty.is_nil();
constexpr size_t size = empty.size();
constexpr uuid_variant variant = empty.variant();
constexpr uuid_version version = empty.version();
}