Begun implementation.

This commit is contained in:
Per Malmberg 2018-03-08 14:21:26 -08:00
parent 24cfe15a79
commit 2071035acf
20 changed files with 14134 additions and 0 deletions

3
.gitignore vendored
View File

@ -30,3 +30,6 @@
*.exe
*.out
*.app
cmake-build-*
.idea/workspace.xml

View File

@ -0,0 +1,29 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<Objective-C-extensions>
<file>
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Import" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Macro" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Typedef" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Enum" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Constant" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Global" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Struct" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="FunctionPredecl" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Function" />
</file>
<class>
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Property" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Synthesize" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InitMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="StaticMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InstanceMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="DeallocMethod" />
</class>
<extensions>
<pair source="cpp" header="h" fileNamingConvention="NONE" />
<pair source="c" header="h" fileNamingConvention="NONE" />
</extensions>
</Objective-C-extensions>
</code_scheme>
</component>

2
.idea/libcron.iml Normal file
View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module classpath="CMake" type="CPP_MODULE" version="4" />

4
.idea/misc.xml Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" />
</project>

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/libcron.iml" filepath="$PROJECT_DIR$/.idea/libcron.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

6
CMakeLists.txt Normal file
View File

@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.9)
add_subdirectory(libcron)
add_subdirectory(test)
add_dependencies(cron_test libcron)

9
libcron/CMakeLists.txt Normal file
View File

@ -0,0 +1,9 @@
cmake_minimum_required(VERSION 3.9)
project(libcron)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wpedantic -fsanitize=address")
add_library(${PROJECT_NAME}
Cron.h
Cron.cpp Task.h CronTime.h TimeTypes.h CronTime.cpp)

19
libcron/Cron.cpp Normal file
View File

@ -0,0 +1,19 @@
//
// Created by permal on 3/8/18.
//
#include <functional>
#include "Cron.h"
bool libcron::Cron::add_schedule(const std::string &schedule, std::function<void()> work)
{
auto cron = CronTime::create(schedule);
bool res = cron.is_valid();
if (res)
{
items.emplace(Task(cron, std::move(work)));
}
return res;
}

18
libcron/Cron.h Normal file
View File

@ -0,0 +1,18 @@
#pragma once
#include <string>
#include <chrono>
#include <queue>
#include "Task.h"
namespace libcron
{
class Cron
{
public:
bool add_schedule(const std::string& schedule, std::function<void()> work);
private:
std::priority_queue<Task> items{};
};
}

71
libcron/CronTime.cpp Normal file
View File

@ -0,0 +1,71 @@
#include "CronTime.h"
namespace libcron
{
CronTime CronTime::create(const std::string& cron_expression)
{
CronTime c;
c.parse(cron_expression);
return std::move(c);
}
CronTime::CronTime()
: month_names({"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}),
day_names({"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"})
{
}
void CronTime::parse(const std::string& cron_expression)
{
// First, split on white-space. We expect six parts.
std::regex split{R"#(^\s*(.*?)\s+(.*?)\s+(.*?)\s+(.*?)\s+(.*?)\s+(.*?)\s*$)#",
std::regex_constants::ECMAScript};
std::smatch match;
if (std::regex_match(cron_expression.begin(), cron_expression.end(), match, split))
{
valid = validate_numeric<Seconds>(match[1], seconds);
valid &= validate_numeric<Minutes>(match[2], minutes);
valid &= validate_numeric<Hours>(match[3], hours);
valid &= validate_numeric<DayOfMonth>(match[4], day_of_month);
valid &= validate_numeric<Months>(match[5], months)
|| validate_literal<Months>(match[5], months, month_names, 1);
valid &= validate_numeric<DayOfWeek>(match[6], day_of_week)
|| validate_literal<DayOfWeek>(match[6], day_of_week, day_names, 0);
}
}
std::vector<std::string> CronTime::split(const std::string& s, char token)
{
std::vector<std::string> res;
std::string r = "[";
r += token;
r += "]";
std::regex splitter{r, std::regex_constants::ECMAScript};
std::copy(std::sregex_token_iterator(s.begin(), s.end(), splitter, -1),
std::sregex_token_iterator(),
std::back_inserter(res));
return res;
}
bool CronTime::is_number(const std::string& s)
{
// Find any character that isn't a number.
return !s.empty()
&& std::find_if(s.begin(), s.end(),
[](char c)
{ return !std::isdigit(c); }) == s.end();
}
bool CronTime::is_between(int32_t value, int32_t low_limit, int32_t high_limt)
{
return value >= low_limit && value <= high_limt;
}
}

285
libcron/CronTime.h Normal file
View File

@ -0,0 +1,285 @@
#pragma once
#include <set>
#include "TimeTypes.h"
#include <regex>
#include <chrono>
#include <string>
#include <vector>
namespace libcron
{
/*
Cron format, 6 parts:
seconds (0 - 59)
minute (0 - 59)
hour (0 - 23)
day of month (1 - 31)
month (1 - 12)
day of week (0 - 6) (Sunday to Saturday;
7 is also Sunday on some systems)
* * * * * *
Allowed formats:
Special characters: '*', meaning the entire range.
Ranges: 1,2,4-6
Result: 1,2,4,5,6
Steps: 1/2
Result: 1,3,5,7...<max>
For day of month, these strings are valid, case insensitive:
SUN, MON, TUE, WED, THU, FRI, SAT
Example: MON-THU,SAT
For month, these strings are valid, case insensitive:
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
Example: JAN,MAR,SEP-NOV
Each part is separated by one or more whitespaces. It is thus important to keep
whitespaces out of the respective parts.
Valid:
* * * * * *
0,3,40-50 * * * * *
Invalid:
0, 3, 40-50 * * * * *
*/
class CronTime
{
public:
static CronTime create(const std::string& cron_expression);
CronTime();
bool operator<(const CronTime& other) const
{
return next_run_time < other.next_run_time;
}
bool is_valid() const
{
return valid;
}
#ifndef EXPOSE_PRIVATE_PARTS
private:
#endif
void parse(const std::string& cron_expression);
template<typename T>
bool validate_numeric(const std::string& s, std::set<T>& numbers);
template<typename T>
bool validate_literal(const std::string& s,
std::set<T>& numbers,
const std::vector<std::string>& names,
int32_t name_offset);
template<typename T>
bool process_parts(const std::vector<std::string>& parts, std::set<T>& numbers);
template<typename T>
bool add_number(std::set<T>& set, int32_t number);
template<typename T>
bool is_within_limits(int32_t low, int32_t high);
template<typename T>
bool get_range(const std::string& s, T& low, T& high);
template<typename T>
uint8_t value_of(T t)
{
return static_cast<uint8_t>(t);
}
std::vector<std::string> split(const std::string& s, char token);
bool is_number(const std::string& s);
bool is_between(int32_t value, int32_t low_limit, int32_t high_limit);
std::chrono::system_clock::time_point next_run_time{};
std::set<Seconds> seconds{};
std::set<Minutes> minutes{};
std::set<Hours> hours{};
std::set<DayOfMonth> day_of_month{};
std::set<Months> months{};
std::set<DayOfWeek> day_of_week{};
bool valid = false;
std::vector<std::string> month_names;
std::vector<std::string> day_names;
template<typename T>
void add_full_range(std::set<T>& set);
};
template<typename T>
bool CronTime::validate_numeric(const std::string& s, std::set<T>& numbers)
{
std::vector<std::string> parts = split(s, ',');
return process_parts(parts, numbers);
}
template<typename T>
bool CronTime::validate_literal(const std::string& s,
std::set<T>& numbers,
const std::vector<std::string>& names,
int32_t name_offset)
{
std::vector<std::string> parts = split(s, ',');
// Replace each found name with the corresponding value.
for (const auto& name : names)
{
std::regex m(name, std::regex_constants::ECMAScript | std::regex_constants::icase);
for (size_t i = 0; i < parts.size(); ++i)
{
std::string replaced;
std::regex_replace(std::back_inserter(replaced), parts[i].begin(), parts[i].end(), m,
std::to_string(name_offset));
parts[i] = replaced;
}
name_offset++;
}
return process_parts(parts, numbers);
}
template<typename T>
bool CronTime::process_parts(const std::vector<std::string>& parts, std::set<T>& numbers)
{
bool res = true;
T left;
T right;
for (const auto& p : parts)
{
if (p == "*")
{
add_full_range<T>(numbers);
}
else if (is_number(p))
{
res &= add_number<T>(numbers, std::stoi(p));
}
else if (get_range<T>(p, left, right))
{
// A range can be written as both 1-22 or 22-1, meaning totally different ranges.
// First case is 1...22 while 22-1 is only four hours: 22, 23, 0, 1.
if (left <= right)
{
for (auto v = value_of(left); v <= value_of(right); ++v)
{
res &= add_number(numbers, v);
}
}
else
{
// 'left' and 'right' are not in value order. First, get values between 'left' and T::Last, inclusive
for (auto v = value_of(left); v <= value_of(T::Last); ++v)
{
res &= add_number(numbers, v);
}
// Next, get values between T::First and 'right', inclusive.
for (auto v = value_of(T::First); v <= value_of(right); ++v)
{
res &= add_number(numbers, v);
}
}
}
else
{
res = false;
}
}
return res;
}
template<typename T>
bool CronTime::get_range(const std::string& s, T& low, T& high)
{
bool res = false;
auto value_range = R"#((\d+)-(\d+))#";
std::regex range(value_range, std::regex_constants::ECMAScript);
std::smatch match;
if (std::regex_match(s.begin(), s.end(), match, range))
{
auto left = std::stoi(match[1].str().c_str());
auto right = std::stoi(match[2].str().c_str());
if (is_within_limits<T>(left, right))
{
low = static_cast<T>(left);
high = static_cast<T>(right);
res = true;
}
}
return res;
}
template<typename T>
void CronTime::add_full_range(std::set<T>& set)
{
for (auto v = value_of(T::First); v <= value_of(T::Last); ++v)
{
if (set.find(static_cast<T>(v)) == set.end())
{
set.emplace(static_cast<T>(v));
}
}
}
template<typename T>
bool CronTime::add_number(std::set<T>& set, int32_t number)
{
bool res = true;
// Don't add if already there
if (set.find(static_cast<T>(number)) == set.end())
{
// Check range
if (is_within_limits<T>(number, number))
{
set.emplace(static_cast<T>(number));
}
else
{
res = false;
}
}
return res;
}
template<typename T>
bool CronTime::is_within_limits(int32_t low, int32_t high)
{
return is_between(low, value_of(T::First), value_of(T::Last))
&& is_between(high, value_of(T::First), value_of(T::Last));
}
}

26
libcron/Task.h Normal file
View File

@ -0,0 +1,26 @@
#pragma once
#include <functional>
#include "CronTime.h"
namespace libcron
{
class Task
{
public:
Task(CronTime time, std::function<void()> task)
: time(std::move(time)), task(std::move(task))
{
}
bool operator<(const Task& other) const
{
return time < other.time;
}
private:
CronTime time{};
std::function<void()> task;
};
}

43
libcron/TimeTypes.h Normal file
View File

@ -0,0 +1,43 @@
#pragma once
#include <cstdint>
namespace libcron
{
enum class Seconds : int8_t
{
First = 0,
Last = 59
};
enum class Minutes : int8_t
{
First = 0,
Last = 59
};
enum class Hours : int8_t
{
First = 0,
Last = 23
};
enum class DayOfMonth : uint8_t
{
First = 1,
Last = 31
};
enum class Months : uint8_t
{
First = 1,
Last = 12
};
enum class DayOfWeek : uint8_t
{
// Sunday = 0 ... Saturday = 6
First = 0,
Last = 6,
};
}

19
test/CMakeLists.txt Normal file
View File

@ -0,0 +1,19 @@
cmake_minimum_required(VERSION 3.6)
project(cron_test)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wpedantic -fsanitize=address -lasan")
add_definitions(-DEXPOSE_PRIVATE_PARTS)
include_directories(
externals/Catch2/single_include/
..
)
add_executable(
${PROJECT_NAME}
test.cpp
)
target_link_libraries(${PROJECT_NAME} libcron)

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

198
test/test.cpp Normal file
View File

@ -0,0 +1,198 @@
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include <catch.hpp>
#include <libcron/Cron.h>
#include <libcron/CronTime.h>
using namespace libcron;
template<typename T>
bool has_value_range(const std::set<T>& set, uint8_t low, uint8_t high)
{
bool found = true;
for (auto i = low; found && i <= high; ++i)
{
found &= set.find(static_cast<T>(i)) != set.end();
}
return found;
}
template<typename T>
bool has_any_in_range(const std::set<T>& set, uint8_t low, uint8_t high)
{
bool found = false;
for (auto i = low; !found && i <= high; ++i)
{
found |= set.find(static_cast<T>(i)) != set.end();
}
return found;
}
SCENARIO("Numerical inputs")
{
GIVEN("Valid numerical inputs")
{
WHEN("Creating with all stars")
{
THEN("All parts are filled")
{
auto c = CronTime::create("* * * * * *");
REQUIRE(c.is_valid());
REQUIRE(c.seconds.size() == 60);
REQUIRE(has_value_range(c.seconds, 0, 59));
REQUIRE(c.minutes.size() == 60);
REQUIRE(has_value_range(c.minutes, 0, 59));
REQUIRE(c.hours.size() == 24);
REQUIRE(has_value_range(c.hours, 0, 23));
REQUIRE(c.day_of_month.size() == 31);
REQUIRE(has_value_range(c.day_of_month, 1, 31));
REQUIRE(c.day_of_week.size() == 7);
REQUIRE(has_value_range(c.day_of_week, 0, 6));
}
}
AND_WHEN("Using full forward range")
{
THEN("Ranges are correct")
{
auto c = CronTime::create("* 0-59 * * * *");
REQUIRE(c.is_valid());
REQUIRE(c.seconds.size() == 60);
REQUIRE(c.minutes.size() == 60);
REQUIRE(c.hours.size() == 24);
REQUIRE(c.day_of_month.size() == 31);
REQUIRE(c.day_of_week.size() == 7);
REQUIRE(has_value_range(c.seconds, 0, 59));
}
}
AND_WHEN("Using partial range")
{
THEN("Ranges are correct")
{
auto c = CronTime::create("* * * 20-30 * *");
REQUIRE(c.is_valid());
REQUIRE(c.seconds.size() == 60);
REQUIRE(c.minutes.size() == 60);
REQUIRE(c.hours.size() == 24);
REQUIRE(c.day_of_month.size() == 11);
REQUIRE(c.day_of_week.size() == 7);
REQUIRE(has_value_range(c.day_of_month, 20, 30));
}
}
AND_WHEN("Using backward range")
{
THEN("Number of hours are correct")
{
auto c = CronTime::create("* * 20-5 * * *");
REQUIRE(c.is_valid());
REQUIRE(c.hours.size() == 10);
REQUIRE(c.hours.find(Hours::First) != c.hours.end());
}
}
AND_WHEN("Using various ranges")
{
THEN("Validation succeeds")
{
REQUIRE(CronTime::create("0-59 * * * * *").is_valid());
REQUIRE(CronTime::create("* 0-59 * * * *").is_valid());
REQUIRE(CronTime::create("* * 0-23 * * *").is_valid());
REQUIRE(CronTime::create("* * * 1-31 * *").is_valid());
REQUIRE(CronTime::create("* * * * 1-12 *").is_valid());
REQUIRE(CronTime::create("* * * * * 0-6").is_valid());
}
}
}
GIVEN("Invalid inputs")
{
WHEN("Creating items")
{
THEN("Validation fails")
{
REQUIRE_FALSE(CronTime::create("").is_valid());
REQUIRE_FALSE(CronTime::create("-").is_valid());
REQUIRE_FALSE(CronTime::create("* ").is_valid());
REQUIRE_FALSE(CronTime::create("* 0-60 * * * *").is_valid());
REQUIRE_FALSE(CronTime::create("* * 0-25 * * *").is_valid());
REQUIRE_FALSE(CronTime::create("* * * 1-32 * *").is_valid());
REQUIRE_FALSE(CronTime::create("* * * * 1-13 *").is_valid());
REQUIRE_FALSE(CronTime::create("* * * * * 0-7").is_valid());
REQUIRE_FALSE(CronTime::create("* * * 0-31 * *").is_valid());
REQUIRE_FALSE(CronTime::create("* * * * 0-12 *").is_valid());
REQUIRE_FALSE(CronTime::create("60 * * * * *").is_valid());
REQUIRE_FALSE(CronTime::create("* 60 * * * *").is_valid());
REQUIRE_FALSE(CronTime::create("* * 25 * * *").is_valid());
REQUIRE_FALSE(CronTime::create("* * * 32 * *").is_valid());
REQUIRE_FALSE(CronTime::create("* * * * 13 *").is_valid());
REQUIRE_FALSE(CronTime::create("* * * * * 7").is_valid());
}
}
}
}
SCENARIO("Literal input")
{
GIVEN("Literal inputs")
{
WHEN("Using literal ranges")
{
THEN("Range is valid")
{
auto c = CronTime::create("* * * * JAN-MAR *");
REQUIRE(c.is_valid());
REQUIRE(has_value_range(c.months, 1, 3));
}
AND_THEN("Range is valid")
{
auto c = CronTime::create("* * * * * SUN-FRI");
REQUIRE(c.is_valid());
REQUIRE(has_value_range(c.day_of_week, 0, 5));
}
}
AND_WHEN("Using both range and specific month")
{
THEN("Range is valid")
{
auto c = CronTime::create("* * * * JAN-MAR,DEC *");
REQUIRE(c.is_valid());
REQUIRE(has_value_range(c.months, 1, 3));
REQUIRE_FALSE(has_any_in_range(c.months, 4, 11));
REQUIRE(has_value_range(c.months, 12, 12));
}
AND_THEN("Range is valid")
{
auto c = CronTime::create("* * * * JAN-MAR,DEC FRI,MON,THU");
REQUIRE(c.is_valid());
REQUIRE(has_value_range(c.months, 1, 3));
REQUIRE_FALSE(has_any_in_range(c.months, 4, 11));
REQUIRE(has_value_range(c.months, 12, 12));
REQUIRE(has_value_range(c.day_of_week, 5, 5));
REQUIRE(has_value_range(c.day_of_week, 1, 1));
REQUIRE(has_value_range(c.day_of_week, 4, 4));
REQUIRE_FALSE(has_any_in_range(c.day_of_week, 0, 0));
REQUIRE_FALSE(has_any_in_range(c.day_of_week, 2, 3));
REQUIRE_FALSE(has_any_in_range(c.day_of_week, 6, 6));
}
}
AND_WHEN("Using backward range")
{
THEN("Range is valid")
{
auto c = CronTime::create("* * * * APR-JAN *");
REQUIRE(c.is_valid());
REQUIRE(has_value_range(c.months, 4, 12));
REQUIRE(has_value_range(c.months, 1, 1));
REQUIRE_FALSE(has_any_in_range(c.months, 2, 3));
}
AND_THEN("Range is valid")
{
auto c = CronTime::create("* * * * * sat-tue,wed");
REQUIRE(c.is_valid());
REQUIRE(has_value_range(c.day_of_week, 6, 6)); // Has saturday
REQUIRE(has_value_range(c.day_of_week, 0, 3)); // Has sun, mon, tue, wed
REQUIRE_FALSE(has_any_in_range(c.day_of_week, 4, 5)); // Does not have thu or fri.
}
}
}
}