PokemonScriptTester/src/Tester/TestFunctions.hpp

78 lines
3.1 KiB
C++

#ifndef POKEMONSCRIPTTESTER_TESTFUNCTIONS_HPP
#define POKEMONSCRIPTTESTER_TESTFUNCTIONS_HPP
#include <angelscript.h>
#include "AssertionFailed.hpp"
#include "TestEnvironment.hpp"
class TestFunctions {
private:
struct AssertionData {
std::string FileName;
size_t Line;
};
static AssertionData GetAssertionData() {
auto* ctx = asGetActiveContext();
TestEnvironment* env = static_cast<TestEnvironment*>(ctx->GetUserData());
env->AssertionCount += 1;
auto filename = ctx->GetFunction()->GetScriptSectionName();
auto line = ctx->GetLineNumber();
return AssertionData{
.FileName = filename,
.Line = (size_t)line,
};
}
static bool Assert(bool value) {
if (!value) {
auto data = GetAssertionData();
throw AssertionFailed(data.FileName, data.Line);
}
return true;
}
#define GetEqualityMessage(expected, actual) \
std::string eqMsg; \
{ \
std::ostringstream ss; \
ss << "Expected: '" << std::to_string(expected) << "', but was: '" << std::to_string(actual) << "'"; \
eqMsg = ss.str(); \
}
static bool AssertEqualsI32(i32 expected, i32 actual) {
if (expected != actual) {
auto data = GetAssertionData();
GetEqualityMessage(expected, actual);
throw AssertionFailed(data.FileName, data.Line, eqMsg);
}
return true;
}
static bool AssertEqualsString(const std::string& expected, const std::string& actual) {
if (expected != actual) {
auto data = GetAssertionData();
std::string eqMsg;
{
std::ostringstream ss;
ss << "Expected: '" << expected << "', but was: '" << actual << "'";
eqMsg = ss.str();
}
throw AssertionFailed(data.FileName, data.Line, eqMsg);
}
return true;
}
public:
static void Register(AngelScriptResolver* scriptResolver) {
auto engine = scriptResolver->GetBuilder().GetEngine();
Ensure(engine->RegisterGlobalFunction("bool Assert(bool expression)", asFUNCTION(Assert), asCALL_CDECL) >= 0);
Ensure(engine->RegisterGlobalFunction("bool AssertEquals(int expected, int actual)",
asFUNCTION(AssertEqualsI32), asCALL_CDECL) >= 0);
Ensure(engine->RegisterGlobalFunction("bool AssertEquals(const string &in expected, const string &in actual)",
asFUNCTION(AssertEqualsString), asCALL_CDECL) >= 0);
}
};
#endif // POKEMONSCRIPTTESTER_TESTFUNCTIONS_HPP