Skip to content

Instantly share code, notes, and snippets.

@poseidon4o
Created November 3, 2014 22:05
Show Gist options
  • Save poseidon4o/f600f23fb067ad46c16e to your computer and use it in GitHub Desktop.
Save poseidon4o/f600f23fb067ad46c16e to your computer and use it in GitHub Desktop.
Very simple class allowing you to make and run test cases based on lambdas as callbacks.
#include <string>
#include "SimpleTest.h"
using namespace std;
// assumes dest has enough space for source
const char * str_concat(char * dest, const char * source) {
while (*dest) ++dest;
while (*source) {
*(dest++) = *(source++);
}
return dest;
}
int main() {
SimpleTesting concat("Concat");
const char * app = "append!";
const char * test = "Test";
concat.add("append to empty", [app, test](SimpleTesting * t) {
char buff[256] = { 0, };
str_concat(buff, test);
t->equal(string(buff), string("Test"));
});
concat.add("multiple concats", [app, test](SimpleTesting * t) {
char buff[256] = { 0, };
str_concat(buff, test);
str_concat(buff, app);
t->equal(string(buff), string("Testappend!"));
});
concat.add("middle of string append", [test](SimpleTesting * t) {
char buff[256] = "012345678";
str_concat(buff + 3, test);
t->equal(string(buff), string("012345678Test"));
});
concat.add("multiple appends", [](SimpleTesting * t) {
char buff[256] = { 0, }, app[2] = { 0, };
for (int c = 0; c < 10; ++c) {
app[0] = 'a' + c;
str_concat(buff, app);
}
t->equal(string(buff), string("abcdefghij"));
});
concat.run();
cin.get();
return 0;
}
#pragma once
#include <vector>
#include <functional>
#include <string>
#include <utility>
#include <iostream>
class SimpleTesting {
public:
typedef std::function<void(SimpleTesting *)> case_callback;
private:
std::vector<std::pair<std::string, case_callback>> cases;
std::string name;
std::string * current_test;
int failed;
std::ostream & output;
bool ran;
public:
SimpleTesting(const std::string & name, std::ostream & out = std::cout): output(out), name(name), current_test(NULL), failed(0), ran(false) {}
void add(const std::string & name, case_callback fn) {
cases.push_back(make_pair(name, fn));
}
template <typename T>
void equal(const T & actual, const T & expected) {
if ( !(actual == expected) ) {
output << "FAIL: " << name << "." << (current_test ? *current_test : "unknown") << " actual:" << actual << " expected:" << expected << std::endl;
++failed;
}
}
void run() {
if (ran) {
return;
}
ran = true;
for (int c = 0; c < cases.size(); ++c) {
current_test = &cases[c].first;
cases[c].second(this);
}
output << name << ": " << cases.size() << " tests ran, " << failed << " failed";
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment