Sync with BGFX (nw)

This commit is contained in:
Miodrag Milanovic 2016-05-16 14:17:04 +02:00
parent 7842148635
commit 71379c5648
88 changed files with 10580 additions and 5369 deletions

View File

@ -153,6 +153,14 @@
Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code.
Also read releases logs https://github.com/ocornut/imgui/releases for more details.
- 2016/05/12 (1.49) - title bar (using TitleBg/TitleBgActive colors) isn't rendered over a window background (WindowBg color) anymore.
If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given that color and the WindowBg color.
ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
{
float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a);
}
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
- 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
@ -556,6 +564,9 @@
- style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle
- text: simple markup language for color change?
- font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier.
- font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance
- font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback.
- font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize)
- font: fix AddRemapChar() to work before font has been built.
- log: LogButtons() options for specifying depth and/or hiding depth slider
- log: have more control over the log scope (e.g. stop logging when leaving current tree node scope)
@ -747,9 +758,9 @@ ImGuiStyle::ImGuiStyle()
Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input
Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f);
Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f);
Colors[ImGuiCol_TitleBg] = ImVec4(0.50f, 0.50f, 1.00f, 0.45f);
Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);
Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
Colors[ImGuiCol_TitleBgActive] = ImVec4(0.50f, 0.50f, 1.00f, 0.55f);
Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);
Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);
Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);
Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);
@ -4057,7 +4068,7 @@ bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_us
bg_color.w = bg_alpha;
bg_color.w *= style.Alpha;
if (bg_color.w > 0.0f)
window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding);
window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 15 : 4|8);
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
@ -5335,7 +5346,12 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
SetHoveredID(id);
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) // Most common type
// | CLICKING | HOLDING with ImGuiButtonFlags_Repeat
// PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds
// PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
// PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
// PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
{
SetActiveID(id, window); // Hold on ID
FocusWindow(window);
@ -5348,10 +5364,14 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
}
if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
{
pressed = true;
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
pressed = true;
SetActiveID(0);
}
if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && ImGui::IsMouseClicked(0, true))
// 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
// Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && ImGui::IsMouseClicked(0, true))
pressed = true;
}
}
@ -5366,7 +5386,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool
else
{
if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
pressed = true;
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
pressed = true;
SetActiveID(0);
}
}
@ -9181,7 +9202,7 @@ void ImGui::Columns(int columns_count, const char* id, bool border)
continue;
bool hovered, held;
ButtonBehavior(column_rect, column_id, &hovered, &held, true);
ButtonBehavior(column_rect, column_id, &hovered, &held);
if (hovered || held)
g.MouseCursor = ImGuiMouseCursor_ResizeEW;
@ -9491,12 +9512,12 @@ void ImGui::ShowMetricsWindow(bool* p_open)
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
if (show_clip_rects && ImGui::IsItemHovered())
{
ImRect clip_rect = pcmd->ClipRect;
ImRect vtxs_rect;
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
@ -9504,20 +9525,22 @@ void ImGui::ShowMetricsWindow(bool* p_open)
}
if (!pcmd_node_open)
continue;
for (int i = elem_offset; i+2 < elem_offset + (int)pcmd->ElemCount; i += 3)
ImGuiListClipper clipper(pcmd->ElemCount/3, ImGui::GetTextLineHeight()*3 + ImGui::GetStyle().ItemSpacing.y); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
ImVec2 triangles_pos[3];
char buf[300], *buf_p = buf;
for (int n = 0; n < 3; n++)
ImVec2 triangles_pos[3];
for (int n = 0; n < 3; n++, vtx_i++)
{
ImDrawVert& v = draw_list->VtxBuffer[(draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data[i+n] : i+n];
ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
triangles_pos[n] = v.pos;
buf_p += sprintf(buf_p, "vtx %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", i+n, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (ImGui::IsItemHovered())
overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle
}
clipper.End();
ImGui::TreePop();
}
overlay_draw_list->PopClipRect();

View File

@ -110,7 +110,7 @@ namespace ImGui
IMGUI_API void Render(); // ends the ImGui frame, finalize rendering data, then call your io.RenderDrawListsFn() function if set.
IMGUI_API void Shutdown();
IMGUI_API void ShowUserGuide(); // help block
IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block
IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block. you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)
IMGUI_API void ShowTestWindow(bool* p_open = NULL); // test window demonstrating ImGui features
IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // metrics window for debugging ImGui
@ -261,8 +261,8 @@ namespace ImGui
IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\0
IMGUI_API bool Combo(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1);
IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true);
IMGUI_API bool ColorEdit3(const char* label, float col[3]);
IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true);
IMGUI_API bool ColorEdit3(const char* label, float col[3]); // Hint: 'float col[3]' function argument is same as 'float* col'. You can pass address of first element out of a contiguous set, e.g. &myvector.x
IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); // "
IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); // FIXME-OBSOLETE: This is inconsistent with most of the API and should be obsoleted.
IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float));
IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0));
@ -271,6 +271,7 @@ namespace ImGui
IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL);
// Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds)
// For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, remember than a 'float v[3]' function argument is the same as 'float* v'. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound
IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f);
IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f);
@ -734,7 +735,7 @@ struct ImGuiIO
float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels.
float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging
int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array
float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds. (for actions where 'repeat' is active)
float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.).
float KeyRepeatRate; // = 0.020f // When holding a key/button, rate at which it repeats, in seconds.
void* UserData; // = NULL // Store your own data for retrieval by callbacks.
@ -793,7 +794,7 @@ struct ImGuiIO
// Functions
IMGUI_API void AddInputCharacter(ImWchar c); // Helper to add a new character into InputCharacters[]
IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Helper to add new characters into InputCharacters[] from an UTF-8 string
IMGUI_API void ClearInputCharacters() { InputCharacters[0] = 0; } // Helper to clear the text input buffer
inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Helper to clear the text input buffer
//------------------------------------------------------------------
// Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application
@ -1257,7 +1258,7 @@ struct ImFontConfig
int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
bool PixelSnapH; // false // Align every character to pixel boundary (if enabled, set OversampleH/V to 1)
ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs
const ImWchar* GlyphRanges; // // List of Unicode range (2 value per range, values are inclusive, zero-terminated list)
const ImWchar* GlyphRanges; // // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs).
bool MergeGlyphCenterV; // false // When merging (multiple ImFontInput for one ImFont), vertically center new glyphs instead of aligning their baseline
@ -1276,6 +1277,7 @@ struct ImFontConfig
// 3. Upload the pixels data into a texture within your graphics system.
// 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture.
// 5. Call ClearTexData() to free textures memory on the heap.
// NB: If you use a 'glyph_ranges' array you need to make sure that your array persist up until the ImFont is cleared. We only copy the pointer, not the data.
struct ImFontAtlas
{
IMGUI_API ImFontAtlas();

View File

@ -1218,7 +1218,7 @@ void ImGui::ShowTestWindow(bool* p_open)
ImGui::EndPopup();
}
static ImVec4 color = ImColor(1.0f, 0.0f, 1.0f, 1.0f);
static ImVec4 color = ImColor(0.8f, 0.5f, 1.0f, 1.0f);
ImGui::ColorButton(color);
if (ImGui::BeginPopupContextItem("color context menu"))
{
@ -1554,9 +1554,11 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
{
ImGuiStyle& style = ImGui::GetStyle();
const ImGuiStyle def; // Default style
// You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to the default style)
const ImGuiStyle default_style; // Default style
if (ImGui::Button("Revert Style"))
style = ref ? *ref : def;
style = ref ? *ref : default_style;
if (ref)
{
ImGui::SameLine();
@ -1611,7 +1613,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
{
const ImVec4& col = style.Colors[i];
const char* name = ImGui::GetStyleColName(i);
if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &def.Colors[i]), sizeof(ImVec4)) != 0)
if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0)
ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 22 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
}
ImGui::LogFinish();
@ -1640,9 +1642,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref)
continue;
ImGui::PushID(i);
ImGui::ColorEdit4(name, (float*)&style.Colors[i], true);
if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &def.Colors[i]), sizeof(ImVec4)) != 0)
if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0)
{
ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : def.Colors[i];
ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : default_style.Colors[i];
if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; }
}
ImGui::PopID();
@ -2438,7 +2440,7 @@ static void ShowExampleAppLongText(bool* p_open)
{
// Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper.
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));
ImGuiListClipper clipper(lines, ImGui::GetTextLineHeight());
ImGuiListClipper clipper(lines, ImGui::GetTextLineHeightWithSpacing()); // Here we changed spacing is zero anyway so we could use GetTextLineHeight(), but _WithSpacing() is typically more correct
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
ImGui::Text("%i The quick brown fox jumps over the lazy dog\n", i);
clipper.End();
@ -2461,7 +2463,7 @@ static void ShowExampleAppLongText(bool* p_open)
#else
void ImGui::ShowTestWindow(bool*) {}
void ImGui::ShowUserGuide(bool*) {}
void ImGui::ShowStyleEditor(bool*) {}
void ImGui::ShowUserGuide() {}
void ImGui::ShowStyleEditor(ImGuiStyle*) {}
#endif

View File

@ -138,8 +138,12 @@ https://github.com/mamedev/mame MAME - Multiple Arcade Machine Emulator
https://blackshift.itch.io/blackshift - Blackshift is a grid-based, space-themed
action puzzle game which isn't afraid of complexity — think Chip's Challenge on
crack.
![blackshift-screenshot](https://img.itch.io/aW1hZ2UvNTA3NDkvMjU2OTIzLmpwZw==/original/V%2BbpZD.jpg)
crack.
https://www.youtube.com/watch?v=PUl8612Y-ds
<a href="http://www.youtube.com/watch?feature=player_embedded&v=PUl8612Y-ds
" target="_blank"><img src="http://img.youtube.com/vi/PUl8612Y-ds/0.jpg"
alt="Blackshift Trailer, May 2016"
width="640" height="480" border="0" /></a>
https://eheitzresearch.wordpress.com/415-2/ - Real-Time Polygonal-Light Shading
with Linearly Transformed Cosines, Eric Heitz, Jonathan Dupuy, Stephen Hill and

View File

@ -75,7 +75,7 @@ class ExampleDrawStress : public entry::AppI
void init(int _argc, char** _argv) BX_OVERRIDE
{
Args args(_argc, _argv);
m_width = 1280;
m_height = 720;
m_debug = BGFX_DEBUG_TEXT;
@ -224,7 +224,7 @@ class ExampleDrawStress : public entry::AppI
, m_height
);
imguiBeginScrollArea("Settings", m_width - m_width / 4 - 10, 10, m_width / 4, m_height / 3, &m_scrollArea);
imguiBeginScrollArea("Settings", m_width - m_width / 4 - 10, 10, m_width / 4, m_height / 2, &m_scrollArea);
imguiSeparatorLine();
m_transform = imguiChoose(m_transform
@ -246,6 +246,8 @@ class ExampleDrawStress : public entry::AppI
const bgfx::Stats* stats = bgfx::getStats();
imguiLabel("GPU %0.6f [ms]", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq);
imguiLabel("CPU %0.6f [ms]", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq);
imguiLabel("Waiting for render thread %0.6f [ms]", double(stats->waitRender) * toMs);
imguiLabel("Waiting for submit thread %0.6f [ms]", double(stats->waitSubmit) * toMs);
imguiEndScrollArea();
imguiEndFrame();

View File

@ -513,11 +513,12 @@ struct OcornutImguiContext
void setupStyle(bool _dark)
{
// Doug Binks' color scheme
// Doug Binks' darl color scheme
// https://gist.github.com/dougbinks/8089b4bbaccaaf6fa204236978d165a9
ImGuiStyle& style = ImGui::GetStyle();
style.FrameRounding = 3.0f;
// light style from Pacome Danhiez (user itamago)
// https://github.com/ocornut/imgui/pull/511#issuecomment-175719267
style.Colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
style.Colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f);

View File

@ -640,6 +640,9 @@ namespace bgfx
uint64_t gpuTimeBegin; //!< GPU frame begin time.
uint64_t gpuTimeEnd; //!< GPU frame end time.
uint64_t gpuTimerFreq; //!< GPU timer frequency.
int64_t waitRender; //!< Render wait time.
int64_t waitSubmit; //!< Submit wait time.
};
/// Vertex declaration.

View File

@ -307,6 +307,8 @@ typedef struct bgfx_stats
uint64_t gpuTimeEnd;
uint64_t gpuTimerFreq;
int64_t waitRender;
int64_t waitSubmit;
} bgfx_stats_t;
/**/

View File

@ -3892,6 +3892,7 @@ namespace bgfx
bool ok = m_gameSem.wait();
BX_CHECK(ok, "Semaphore wait failed."); BX_UNUSED(ok);
m_render->m_waitSubmit = bx::getHPCounter()-start;
m_submit->m_perfStats.waitSubmit = m_submit->m_waitSubmit;
}
}
@ -3912,6 +3913,7 @@ namespace bgfx
bool ok = m_renderSem.wait();
BX_CHECK(ok, "Semaphore wait failed."); BX_UNUSED(ok);
m_submit->m_waitRender = bx::getHPCounter() - start;
m_submit->m_perfStats.waitRender = m_submit->m_waitRender;
}
}

View File

@ -1,20 +0,0 @@
Copyright (c) 2006 Noel Llopis and Charles Nicholson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,68 +0,0 @@
UnitTest++ README
Version: v1.4
Last update: 2008-10-30
UnitTest++ is free software. You may copy, distribute, and modify it under
the terms of the License contained in the file COPYING distributed
with this package. This license is the same as the MIT/X Consortium
license.
See src/tests/TestUnitTest++.cpp for usage.
Authors:
Noel Llopis (llopis@convexhull.com)
Charles Nicholson (charles.nicholson@gmail.com)
Contributors:
Jim Tilander
Kim Grasman
Jonathan Jansson
Dirck Blaskey
Rory Driscoll
Dan Lind
Matt Kimmel -- Submitted with permission from Blue Fang Games
Anthony Moralez
Jeff Dixon
Randy Coulman
Lieven van der Heide
Release notes:
--------------
Version 1.4 (2008-10-30)
- CHECK macros work at arbitrary stack depth from inside TESTs.
- Remove obsolete TEST_UTILITY macros
- Predicated test execution (via TestRunner::RunTestsIf)
- Better exception handling for fixture ctors/dtors.
- VC6/7/8/9 support
Version 1.3 (2007-4-22)
- Removed dynamic memory allocations (other than streams)
- MinGW support
- Consistent (native) line endings
- Minor bug fixing
Version 1.2 (2006-10-29)
- First pass at documentation.
- More detailed error crash catching in fixtures.
- Standard streams used for printing objects under check. This should allow the
use of standard class types such as std::string or other custom classes with
stream operators to ostream.
- Standard streams can be optionally compiled off by defining UNITTEST_USE_CUSTOM_STREAMS
in Config.h
- Added named test suites
- Added CHECK_ARRAY2D_CLOSE
- Posix library name is libUnitTest++.a now
- Floating point numbers are postfixed with f in the failure reports
Version 1.1 (2006-04-18)
- CHECK macros do not have side effects even if one of the parameters changes state
- Removed CHECK_ARRAY_EQUAL (too similar to CHECK_ARRAY_CLOSE)
- Added local and global time constraints
- Removed dependencies on strstream
- Improved Posix signal to exception translator
- Failing tests are added to Visual Studio's error list
- Fixed Visual Studio projects to work with spaces in directories
Version 1.0 (2006-03-15)
- Initial release

View File

@ -1,260 +0,0 @@
<html>
<head>
<title>UnitTest++ in brief</title>
</head>
<body>
<h1>UnitTest++ in brief</h1>
<h2>Introduction</h2>
<p>This little document serves as bare-bones documentation for UnitTest++.</p>
<p>For background, goals and license details, see:</p>
<ul>
<li><a href="http://unittest-cpp.sourceforge.net/">The UnitTest++ home page</a></li>
<li><a href="http://gamesfromwithin.com/?p=51">Release announcement</a></li>
</ul>
<p>The documentation, while sparse, aims to be practical, so it should give you enough info to get started using UnitTest++ as fast as possible.</p>
<h2>Building UnitTest++</h2>
<p>Building UnitTest++ will be specific to each platform and build environment, but it should be straightforward.</p>
<h3>Building with Visual Studio</h3>
<p>If you are using Visual Studio, go for either of the provided .sln files, depending on version. There are no prefabricated solutions for versions earlier than VS.NET 2003, but we have had reports of people building UnitTest++ with at least VS.NET 2002.</p>
<h3>Building with Make</h3>
<p>The bundled makefile is written to build with g++. It also needs <code>sed</code> installed in the path, and to be able to use the <code>mv</code> and <code>rm</code> shell commands. The makefile should be usable on most Posix-like platforms.</p>
<p>Do "make all" to generate a library and test executable. A final build step runs all unit tests to make sure that the result works as expected.</p>
<h3>Packaging</h3>
<p>You'll probably want to keep the generated library in a shared space in source control, so you can reuse it for multiple test projects. A redistributable package of UnitTest++ would consist of the generated library file, and all of the header files in <code>UnitTest++/src/</code> and its per-platform subfolders. The <code>tests</code> directory only contains the unit tests for the library, and need not be included.</p>
<h2>Using UnitTest++</h2>
<p>The source code for UnitTest++ comes with a full test suite written <em>using</em> UnitTest++. This is a great place to learn techniques for testing. There is one sample .cpp file: <code>UnitTest++/src/tests/TestUnitTest++.cpp</code>. It covers most of UnitTest++'s features in an easy-to-grasp context, so start there if you want a quick overview of typical usage.</p>
<h3>Getting started</h3>
<p>Listed below is a minimal C++ program to run a failing test through UnitTest++.</p>
<pre>
// test.cpp
#include &lt;UnitTest++.h&gt;
TEST(FailSpectacularly)
{
CHECK(false);
}
int main()
{
return UnitTest::RunAllTests();
}
</pre>
<p><code>UnitTest++.h</code> is a facade header for UnitTest++, so including that should get you all features of the library. All classes and free functions are placed in namespace <code>UnitTest</code>, so you need to either qualify their full names (as with <code>RunAllTests()</code> in the example) or add a <code>using namespace UnitTest;</code> statement in your .cpp files. Note that any mention of UnitTest++ functions and classes in this document assume that the <code>UnitTest</code> namespace has been opened.</p>
<p>Compiling and linking this program with UnitTest++'s static library into an executable, and running it, will produce the following output (details may vary):</p>
<pre>
.\test.cpp(5): error: Failure in FailSpectacularly: false
FAILED: 1 out of 1 tests failed (1 failures).
Test time: 0.00 seconds.
</pre>
<p>UnitTest++ attempts to report every failure in an IDE-friendly format, depending on platform (e.g. you can double-click it in Visual Studio's error list.) The exit code will be the number of failed tests, so that a failed test run always returns a non-zero exit code.</p>
<h3>Test macros</h3>
<p>To add a test, simply put the following code in a .cpp file of your choice:</p>
<pre>
TEST(YourTestName)
{
}
</pre>
<p>The <code>TEST</code> macro contains enough machinery to turn this slightly odd-looking syntax into legal C++, and automatically register the test in a global list. This test list forms the basis of what is executed by <code>RunAllTests()</code>.</p>
<p>If you want to re-use a set of test data for more than one test, or provide setup/teardown for tests, you can use the <code>TEST_FIXTURE</code> macro instead. The macro requires that you pass it a class name that it will instantiate, so any setup and teardown code should be in its constructor and destructor.</p>
<pre>
struct SomeFixture
{
SomeFixture() { /* some setup */ }
~SomeFixture() { /* some teardown */ }
int testData;
};
TEST_FIXTURE(SomeFixture, YourTestName)
{
int temp = testData;
}
</pre>
<p>Note how members of the fixture are used as if they are a part of the test, since the macro-generated test class derives from the provided fixture class.</p>
<h3>Suite macros</h3>
<p>Tests can be grouped into suites, using the <code>SUITE</code> macro. A suite serves as a namespace for test names, so that the same test name can be used in two difference contexts.</p>
<pre>
SUITE(YourSuiteName)
{
TEST(YourTestName)
{
}
TEST(YourOtherTestName)
{
}
}
</pre>
<p>This will place the tests into a C++ namespace called <code>YourSuiteName</code>, and make the suite name available to UnitTest++. <code>RunAllTests()</code> can be called for a specific suite name, so you can use this to build named groups of tests to be run together.</p>
<h3>Simple check macros</h3>
<p>In test cases, we want to check the results of our system under test. UnitTest++ provides a number of check macros that handle comparison and proper failure reporting.</p>
<p>The most basic variety is the boolean <code>CHECK</code> macro:</p>
<pre>
CHECK(false); // fails
</pre>
<p>It will fail if the boolean expression evaluates to false.</p>
<p>For equality checks, it's generally better to use <code>CHECK_EQUAL</code>:</p>
<pre>
CHECK_EQUAL(10, 20); // fails
CHECK_EQUAL("foo", "bar"); // fails
</pre>
<p>Note how <code>CHECK_EQUAL</code> is overloaded for C strings, so you don't have to resort to <code>strcmp</code> or similar. There is no facility for case-insensitive comparison or string searches, so you may have to drop down to a plain boolean <code>CHECK</code> with help from the CRT:</p>
<pre>
CHECK(std::strstr("zaza", "az") != 0); // succeeds
</pre>
<p>For floating-point comparison, equality <a href="http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm">isn't necessarily well-defined</a>, so you should prefer the <code>CHECK_CLOSE</code> macro:</p>
<pre>
CHECK_CLOSE(3.14, 3.1415, 0.01); // succeeds
</pre>
<p>All of the macros are tailored to avoid unintended side-effects, for example:</p>
<pre>
TEST(CheckMacrosHaveNoSideEffects)
{
int i = 4;
CHECK_EQUAL(5, ++i); // succeeds
CHECK_EQUAL(5, i); // succeeds
}
</pre>
<p>The check macros guarantee that the <code>++i</code> expression isn't repeated internally, as demonstrated above.</p>
<h3>Array check macros</h3>
<p>There is a set of check macros for array comparison as well:</p>
<pre>
const float oned[2] = { 10, 20 };
CHECK_ARRAY_EQUAL(oned, oned, 2); // succeeds
CHECK_ARRAY_CLOSE(oned, oned, 2, 0.00); // succeeds
const float twod[2][3] = { {0, 1, 2}, {2, 3, 4} };
CHECK_ARRAY2D_CLOSE(twod, twod, 2, 3, 0.00); // succeeds
</pre>
<p>The array equal macro compares elements using <code>operator==</code>, so <code>CHECK_ARRAY_EQUAL</code> won't work for an array of C strings, for example.</p>
<p>The array close macros are similar to the regular CHECK_CLOSE macro, and are really only useful for scalar types, that can be compared in terms of a difference between two array elements.</p>
<p>Note that the one-dimensional array macros work for <code>std::vector</code> as well, as it can be indexed just as a C array.</p>
<h3>Exception check macros</h3>
<p>Finally, there's a <code>CHECK_THROW</code> macro, which asserts that its enclosed expression throws the specified type:</p>
<pre>
struct TestException {};
CHECK_THROW(throw TestException(), TestException); // succeeds
</pre>
<p>UnitTest++ natively catches exceptions if your test code doesn't. So if your code under test throws any exception UnitTest++ will fail the test and report either using the <code>what()</code> method for <code>std::exception</code> derivatives or just a plain message for unknown exception types.</p>
<p>Should your test or code raise an irrecoverable error (an Access Violation on Win32, for example, or a signal on Linux), UnitTest++ will attempt to map them to an exception and fail the test, just as for other unhandled exceptions.</p>
<h3>Time constraints</h3>
<p>UnitTest++ can fail a test if it takes too long to complete, using so-called time constraints.</p>
<p>They come in two flavors; <em>local</em> and <em>global</em> time constraints.</p>
<p>Local time constraints are limited to the current scope, like so:</p>
<pre>
TEST(YourTimedTest)
{
// Lengthy setup...
{
UNITTEST_TIME_CONSTRAINT(50);
// Do time-critical stuff
}
// Lengthy teardown...
}
</pre>
<p>The test will fail if the "Do time-critical stuff" block takes longer than 50 ms to complete. The time-consuming setup and teardown are not measured, since the time constraint is scope-bound. It's perfectly valid to have multiple local time constraints in the same test, as long as there is only one per block.</p>
<p>A global time constraint, on the other hand, requires that all of the tests in a test run are faster than a specified amount of time. This allows you, when you run a suite of tests, to ask UnitTest++ to fail it entirely if any test exceeds the global constraint. The max time is passed as a parameter to an overload of <code>RunAllTests()</code>.</p>
<p>If you want to use a global time constraint, but have one test that is notoriously slow, you can exempt it from inspection by using the <code>UNITTEST_TIME_CONSTRAINT_EXEMPT</code> macro anywhere inside the test body.</p>
<pre>
TEST(NotoriouslySlowTest)
{
UNITTEST_TIME_CONSTRAINT_EXEMPT();
// Oh boy, this is going to take a while
...
}
</pre>
<h3>Test runners</h3>
<p>The <code>RunAllTests()</code> function has an overload that lets you customize the behavior of the runner, such as global time constraints, custom reporters, which suite to run, etc.</p>
<pre>
int RunAllTests(TestReporter& reporter, TestList const& list, char const* suiteName, int const maxTestTimeInMs);
</pre>
<p>If you attempt to pass custom parameters to <code>RunAllTests()</code>, note that the <code>list</code> parameter should have the value <code>Test::GetTestList()</code>.</p>
<p>The parameterless <code>RunAllTests()</code> is a simple wrapper for this one, with sensible defaults.</p>
<h3>Example setup</h3>
<p>How to create a new test project varies depending on your environment, but here are some directions on common file structure and usage.</p>
<p>The general idea is that you keep one <code>Main.cpp</code> file with the entry-point which calls <code>RunAllTests()</code>.</p>
<p>Then you can simply compile and link new .cpp files at will, typically one per test suite.</p>
<pre>
+ ShaverTests/
|
+- Main.cpp
|
+- TestBrush.cpp
+- TestEngine.cpp
+- TestRazor.cpp
</pre>
<p>Each of the <code>Test*.cpp</code> files will contain one or more <code>TEST</code> macro incantations with the associated test code. There are no source-level dependencies between <code>Main.cpp</code> and <code>Test*.cpp</code>, as the <code>TEST</code> macro handles the registration and setup necessary for <code>RunAllTests()</code> to find all tests compiled into the same final executable.</p>
<p>UnitTest++ does not require this structure, even if this is how the library itself does it. As long as your test project contains one or more <code>TESTs</code> and calls <code>RunAllTests()</code> at one point or another, it will be handled by UnitTest++.</p>
<p>It's common to make the generated executable start as a post-build step, so that merely building your test project will run the tests as well. Since the exit code is the count of failures, a failed test will generally break the build, as most build engines will fail a build if any step returns a non-zero exit code.</p>
</body>
</html>

View File

@ -1,34 +0,0 @@
#include "AssertException.h"
#include <cstring>
namespace UnitTest {
AssertException::AssertException(char const* description, char const* filename, int lineNumber)
: m_lineNumber(lineNumber)
{
using namespace std;
strcpy(m_description, description);
strcpy(m_filename, filename);
}
AssertException::~AssertException() throw()
{
}
char const* AssertException::what() const throw()
{
return m_description;
}
char const* AssertException::Filename() const
{
return m_filename;
}
int AssertException::LineNumber() const
{
return m_lineNumber;
}
}

View File

@ -1,28 +0,0 @@
#ifndef UNITTEST_ASSERTEXCEPTION_H
#define UNITTEST_ASSERTEXCEPTION_H
#include <exception>
namespace UnitTest {
class AssertException : public std::exception
{
public:
AssertException(char const* description, char const* filename, int lineNumber);
virtual ~AssertException() throw();
virtual char const* what() const throw();
char const* Filename() const;
int LineNumber() const;
private:
char m_description[512];
char m_filename[256];
int m_lineNumber;
};
}
#endif

View File

@ -1,122 +0,0 @@
#ifndef UNITTEST_CHECKMACROS_H
#define UNITTEST_CHECKMACROS_H
#include "Checks.h"
#include "AssertException.h"
#include "MemoryOutStream.h"
#include "TestDetails.h"
#include "CurrentTest.h"
#ifdef CHECK
#error UnitTest++ redefines CHECK
#endif
#ifdef CHECK_EQUAL
#error UnitTest++ redefines CHECK_EQUAL
#endif
#ifdef CHECK_CLOSE
#error UnitTest++ redefines CHECK_CLOSE
#endif
#ifdef CHECK_ARRAY_EQUAL
#error UnitTest++ redefines CHECK_ARRAY_EQUAL
#endif
#ifdef CHECK_ARRAY_CLOSE
#error UnitTest++ redefines CHECK_ARRAY_CLOSE
#endif
#ifdef CHECK_ARRAY2D_CLOSE
#error UnitTest++ redefines CHECK_ARRAY2D_CLOSE
#endif
#define CHECK(value) \
do \
{ \
try { \
if (!UnitTest::Check(value)) \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), #value); \
} \
catch (...) { \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
"Unhandled exception in CHECK(" #value ")"); \
} \
} while (0)
#define CHECK_EQUAL(expected, actual) \
do \
{ \
try { \
UnitTest::CheckEqual(*UnitTest::CurrentTest::Results(), expected, actual, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
} \
catch (...) { \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
"Unhandled exception in CHECK_EQUAL(" #expected ", " #actual ")"); \
} \
} while (0)
#define CHECK_CLOSE(expected, actual, tolerance) \
do \
{ \
try { \
UnitTest::CheckClose(*UnitTest::CurrentTest::Results(), expected, actual, tolerance, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
} \
catch (...) { \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
"Unhandled exception in CHECK_CLOSE(" #expected ", " #actual ")"); \
} \
} while (0)
#define CHECK_ARRAY_EQUAL(expected, actual, count) \
do \
{ \
try { \
UnitTest::CheckArrayEqual(*UnitTest::CurrentTest::Results(), expected, actual, count, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
} \
catch (...) { \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
"Unhandled exception in CHECK_ARRAY_EQUAL(" #expected ", " #actual ")"); \
} \
} while (0)
#define CHECK_ARRAY_CLOSE(expected, actual, count, tolerance) \
do \
{ \
try { \
UnitTest::CheckArrayClose(*UnitTest::CurrentTest::Results(), expected, actual, count, tolerance, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
} \
catch (...) { \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
"Unhandled exception in CHECK_ARRAY_CLOSE(" #expected ", " #actual ")"); \
} \
} while (0)
#define CHECK_ARRAY2D_CLOSE(expected, actual, rows, columns, tolerance) \
do \
{ \
try { \
UnitTest::CheckArray2DClose(*UnitTest::CurrentTest::Results(), expected, actual, rows, columns, tolerance, UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__)); \
} \
catch (...) { \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), \
"Unhandled exception in CHECK_ARRAY_CLOSE(" #expected ", " #actual ")"); \
} \
} while (0)
#define CHECK_THROW(expression, ExpectedExceptionType) \
do \
{ \
bool caught_ = false; \
try { expression; } \
catch (ExpectedExceptionType const&) { caught_ = true; } \
catch (...) {} \
if (!caught_) \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(*UnitTest::CurrentTest::Details(), __LINE__), "Expected exception: \"" #ExpectedExceptionType "\" not thrown"); \
} while(0)
#define CHECK_ASSERT(expression) \
CHECK_THROW(expression, UnitTest::AssertException);
#endif

View File

@ -1,50 +0,0 @@
#include "Checks.h"
#include <cstring>
namespace UnitTest {
namespace {
void CheckStringsEqual(TestResults& results, char const* expected, char const* actual,
TestDetails const& details)
{
using namespace std;
if (strcmp(expected, actual))
{
UnitTest::MemoryOutStream stream;
stream << "Expected " << expected << " but was " << actual;
results.OnTestFailure(details, stream.GetText());
}
}
}
void CheckEqual(TestResults& results, char const* expected, char const* actual,
TestDetails const& details)
{
CheckStringsEqual(results, expected, actual, details);
}
void CheckEqual(TestResults& results, char* expected, char* actual,
TestDetails const& details)
{
CheckStringsEqual(results, expected, actual, details);
}
void CheckEqual(TestResults& results, char* expected, char const* actual,
TestDetails const& details)
{
CheckStringsEqual(results, expected, actual, details);
}
void CheckEqual(TestResults& results, char const* expected, char* actual,
TestDetails const& details)
{
CheckStringsEqual(results, expected, actual, details);
}
}

View File

@ -1,158 +0,0 @@
#ifndef UNITTEST_CHECKS_H
#define UNITTEST_CHECKS_H
#include "Config.h"
#include "TestResults.h"
#include "MemoryOutStream.h"
namespace UnitTest {
template< typename Value >
bool Check(Value const value)
{
return !!value; // doing double negative to avoid silly VS warnings
}
template< typename Expected, typename Actual >
void CheckEqual(TestResults& results, Expected const& expected, Actual const& actual, TestDetails const& details)
{
if (!(expected == actual))
{
UnitTest::MemoryOutStream stream;
stream << "Expected " << expected << " but was " << actual;
results.OnTestFailure(details, stream.GetText());
}
}
void CheckEqual(TestResults& results, char const* expected, char const* actual, TestDetails const& details);
void CheckEqual(TestResults& results, char* expected, char* actual, TestDetails const& details);
void CheckEqual(TestResults& results, char* expected, char const* actual, TestDetails const& details);
void CheckEqual(TestResults& results, char const* expected, char* actual, TestDetails const& details);
template< typename Expected, typename Actual, typename Tolerance >
bool AreClose(Expected const& expected, Actual const& actual, Tolerance const& tolerance)
{
return (actual >= (expected - tolerance)) && (actual <= (expected + tolerance));
}
template< typename Expected, typename Actual, typename Tolerance >
void CheckClose(TestResults& results, Expected const& expected, Actual const& actual, Tolerance const& tolerance,
TestDetails const& details)
{
if (!AreClose(expected, actual, tolerance))
{
UnitTest::MemoryOutStream stream;
stream << "Expected " << expected << " +/- " << tolerance << " but was " << actual;
results.OnTestFailure(details, stream.GetText());
}
}
template< typename Expected, typename Actual >
void CheckArrayEqual(TestResults& results, Expected const& expected, Actual const& actual,
int const count, TestDetails const& details)
{
bool equal = true;
for (int i = 0; i < count; ++i)
equal &= (expected[i] == actual[i]);
if (!equal)
{
UnitTest::MemoryOutStream stream;
stream << "Expected [ ";
for (int expectedIndex = 0; expectedIndex < count; ++expectedIndex)
stream << expected[expectedIndex] << " ";
stream << "] but was [ ";
for (int actualIndex = 0; actualIndex < count; ++actualIndex)
stream << actual[actualIndex] << " ";
stream << "]";
results.OnTestFailure(details, stream.GetText());
}
}
template< typename Expected, typename Actual, typename Tolerance >
bool ArrayAreClose(Expected const& expected, Actual const& actual, int const count, Tolerance const& tolerance)
{
bool equal = true;
for (int i = 0; i < count; ++i)
equal &= AreClose(expected[i], actual[i], tolerance);
return equal;
}
template< typename Expected, typename Actual, typename Tolerance >
void CheckArrayClose(TestResults& results, Expected const& expected, Actual const& actual,
int const count, Tolerance const& tolerance, TestDetails const& details)
{
bool equal = ArrayAreClose(expected, actual, count, tolerance);
if (!equal)
{
UnitTest::MemoryOutStream stream;
stream << "Expected [ ";
for (int expectedIndex = 0; expectedIndex < count; ++expectedIndex)
stream << expected[expectedIndex] << " ";
stream << "] +/- " << tolerance << " but was [ ";
for (int actualIndex = 0; actualIndex < count; ++actualIndex)
stream << actual[actualIndex] << " ";
stream << "]";
results.OnTestFailure(details, stream.GetText());
}
}
template< typename Expected, typename Actual, typename Tolerance >
void CheckArray2DClose(TestResults& results, Expected const& expected, Actual const& actual,
int const rows, int const columns, Tolerance const& tolerance, TestDetails const& details)
{
bool equal = true;
for (int i = 0; i < rows; ++i)
equal &= ArrayAreClose(expected[i], actual[i], columns, tolerance);
if (!equal)
{
UnitTest::MemoryOutStream stream;
stream << "Expected [ ";
for (int expectedRow = 0; expectedRow < rows; ++expectedRow)
{
stream << "[ ";
for (int expectedColumn = 0; expectedColumn < columns; ++expectedColumn)
stream << expected[expectedRow][expectedColumn] << " ";
stream << "] ";
}
stream << "] +/- " << tolerance << " but was [ ";
for (int actualRow = 0; actualRow < rows; ++actualRow)
{
stream << "[ ";
for (int actualColumn = 0; actualColumn < columns; ++actualColumn)
stream << actual[actualRow][actualColumn] << " ";
stream << "] ";
}
stream << "]";
results.OnTestFailure(details, stream.GetText());
}
}
}
#endif

View File

@ -1,39 +0,0 @@
#ifndef UNITTEST_CONFIG_H
#define UNITTEST_CONFIG_H
// Standard defines documented here: http://predef.sourceforge.net
#if defined(_MSC_VER)
# pragma warning(disable:4127) // conditional expression is constant
# pragma warning(disable:4702) // unreachable code
# pragma warning(disable:4722) // destructor never returns, potential memory leak
# if (_MSC_VER == 1200) // VC6
# pragma warning(disable:4786)
# pragma warning(disable:4290)
# endif
#endif
#if defined(unix) \
|| defined(__unix__) \
|| defined(__unix) \
|| defined(linux) \
|| defined(__APPLE__) \
|| defined(__NetBSD__) \
|| defined(__OpenBSD__) \
|| defined(__FreeBSD__) \
|| defined(__native_client__) \
|| defined(__riscv)
# define UNITTEST_POSIX
#endif
#if defined(__MINGW32__)
# define UNITTEST_MINGW
#endif
// by default, MemoryOutStream is implemented in terms of std::ostringstream, which can be expensive.
// uncomment this line to use the custom MemoryOutStream (no deps on std::ostringstream).
//#define UNITTEST_USE_CUSTOM_STREAMS
#endif

View File

@ -1,18 +0,0 @@
#include "CurrentTest.h"
#include <cstddef>
namespace UnitTest {
TestResults*& CurrentTest::Results()
{
static TestResults* testResults = NULL;
return testResults;
}
const TestDetails*& CurrentTest::Details()
{
static const TestDetails* testDetails = NULL;
return testDetails;
}
}

View File

@ -1,17 +0,0 @@
#ifndef UNITTEST_CURRENTTESTRESULTS_H
#define UNITTEST_CURRENTTESTRESULTS_H
namespace UnitTest {
class TestResults;
class TestDetails;
namespace CurrentTest
{
TestResults*& Results();
const TestDetails*& Details();
}
}
#endif

View File

@ -1,28 +0,0 @@
#include "DeferredTestReporter.h"
#include "TestDetails.h"
using namespace UnitTest;
void DeferredTestReporter::ReportTestStart(TestDetails const& details)
{
m_results.push_back(DeferredTestResult(details.suiteName, details.testName));
}
void DeferredTestReporter::ReportFailure(TestDetails const& details, char const* failure)
{
DeferredTestResult& r = m_results.back();
r.failed = true;
r.failures.push_back(DeferredTestResult::Failure(details.lineNumber, failure));
r.failureFile = details.filename;
}
void DeferredTestReporter::ReportTestFinish(TestDetails const&, float secondsElapsed)
{
DeferredTestResult& r = m_results.back();
r.timeElapsed = secondsElapsed;
}
DeferredTestReporter::DeferredTestResultList& DeferredTestReporter::GetResults()
{
return m_results;
}

View File

@ -1,29 +0,0 @@
#ifndef UNITTEST_DEFERREDTESTREPORTER_H
#define UNITTEST_DEFERREDTESTREPORTER_H
#include "TestReporter.h"
#include "DeferredTestResult.h"
#include "Config.h"
#include <vector>
namespace UnitTest
{
class DeferredTestReporter : public TestReporter
{
public:
virtual void ReportTestStart(TestDetails const& details);
virtual void ReportFailure(TestDetails const& details, char const* failure);
virtual void ReportTestFinish(TestDetails const& details, float secondsElapsed);
typedef std::vector< DeferredTestResult > DeferredTestResultList;
DeferredTestResultList& GetResults();
private:
DeferredTestResultList m_results;
};
}
#endif

View File

@ -1,29 +0,0 @@
#include "DeferredTestResult.h"
#include "Config.h"
namespace UnitTest
{
DeferredTestResult::DeferredTestResult()
: suiteName("")
, testName("")
, failureFile("")
, timeElapsed(0.0f)
, failed(false)
{
}
DeferredTestResult::DeferredTestResult(char const* suite, char const* test)
: suiteName(suite)
, testName(test)
, failureFile("")
, timeElapsed(0.0f)
, failed(false)
{
}
DeferredTestResult::~DeferredTestResult()
{
}
}

View File

@ -1,32 +0,0 @@
#ifndef UNITTEST_DEFERREDTESTRESULT_H
#define UNITTEST_DEFERREDTESTRESULT_H
#include "Config.h"
#include <string>
#include <vector>
namespace UnitTest
{
struct DeferredTestResult
{
DeferredTestResult();
DeferredTestResult(char const* suite, char const* test);
~DeferredTestResult();
std::string suiteName;
std::string testName;
std::string failureFile;
typedef std::pair< int, std::string > Failure;
typedef std::vector< Failure > FailureVec;
FailureVec failures;
float timeElapsed;
bool failed;
};
}
#endif //UNITTEST_DEFERREDTESTRESULT_H

View File

@ -1,46 +0,0 @@
#ifndef UNITTEST_EXECUTE_TEST_H
#define UNITTEST_EXECUTE_TEST_H
#include "TestDetails.h"
#include "MemoryOutStream.h"
#include "AssertException.h"
#include "CurrentTest.h"
#ifdef UNITTEST_POSIX
#include "Posix/SignalTranslator.h"
#endif
namespace UnitTest {
template< typename T >
void ExecuteTest(T& testObject, TestDetails const& details)
{
CurrentTest::Details() = &details;
try
{
#ifdef UNITTEST_POSIX
UNITTEST_THROW_SIGNALS
#endif
testObject.RunImpl();
}
catch (AssertException const& e)
{
CurrentTest::Results()->OnTestFailure(
TestDetails(details.testName, details.suiteName, e.Filename(), e.LineNumber()), e.what());
}
catch (std::exception const& e)
{
MemoryOutStream stream;
stream << "Unhandled exception: " << e.what();
CurrentTest::Results()->OnTestFailure(details, stream.GetText());
}
catch (...)
{
CurrentTest::Results()->OnTestFailure(details, "Unhandled exception: Crash!");
}
}
}
#endif

View File

@ -1,149 +0,0 @@
#include "MemoryOutStream.h"
#ifndef UNITTEST_USE_CUSTOM_STREAMS
namespace UnitTest {
char const* MemoryOutStream::GetText() const
{
m_text = this->str();
return m_text.c_str();
}
}
#else
#include <cstring>
#include <cstdio>
namespace UnitTest {
namespace {
template<typename ValueType>
void FormatToStream(MemoryOutStream& stream, char const* format, ValueType const& value)
{
using namespace std;
char txt[32];
sprintf(txt, format, value);
stream << txt;
}
int RoundUpToMultipleOfPow2Number (int n, int pow2Number)
{
return (n + (pow2Number - 1)) & ~(pow2Number - 1);
}
}
MemoryOutStream::MemoryOutStream(int const size)
: m_capacity (0)
, m_buffer (0)
{
GrowBuffer(size);
}
MemoryOutStream::~MemoryOutStream()
{
delete [] m_buffer;
}
char const* MemoryOutStream::GetText() const
{
return m_buffer;
}
MemoryOutStream& MemoryOutStream::operator << (char const* txt)
{
using namespace std;
int const bytesLeft = m_capacity - (int)strlen(m_buffer);
int const bytesRequired = (int)strlen(txt) + 1;
if (bytesRequired > bytesLeft)
{
int const requiredCapacity = bytesRequired + m_capacity - bytesLeft;
GrowBuffer(requiredCapacity);
}
strcat(m_buffer, txt);
return *this;
}
MemoryOutStream& MemoryOutStream::operator << (int const n)
{
FormatToStream(*this, "%i", n);
return *this;
}
MemoryOutStream& MemoryOutStream::operator << (long const n)
{
FormatToStream(*this, "%li", n);
return *this;
}
MemoryOutStream& MemoryOutStream::operator << (unsigned long const n)
{
FormatToStream(*this, "%lu", n);
return *this;
}
MemoryOutStream& MemoryOutStream::operator << (float const f)
{
FormatToStream(*this, "%ff", f);
return *this;
}
MemoryOutStream& MemoryOutStream::operator << (void const* p)
{
FormatToStream(*this, "%p", p);
return *this;
}
MemoryOutStream& MemoryOutStream::operator << (unsigned int const s)
{
FormatToStream(*this, "%u", s);
return *this;
}
MemoryOutStream& MemoryOutStream::operator <<(double const d)
{
FormatToStream(*this, "%f", d);
return *this;
}
int MemoryOutStream::GetCapacity() const
{
return m_capacity;
}
void MemoryOutStream::GrowBuffer(int const desiredCapacity)
{
int const newCapacity = RoundUpToMultipleOfPow2Number(desiredCapacity, GROW_CHUNK_SIZE);
using namespace std;
char* buffer = new char[newCapacity];
if (m_buffer)
strcpy(buffer, m_buffer);
else
strcpy(buffer, "");
delete [] m_buffer;
m_buffer = buffer;
m_capacity = newCapacity;
}
}
#endif

View File

@ -1,68 +0,0 @@
#ifndef UNITTEST_MEMORYOUTSTREAM_H
#define UNITTEST_MEMORYOUTSTREAM_H
#include "Config.h"
#ifndef UNITTEST_USE_CUSTOM_STREAMS
#include <sstream>
namespace UnitTest
{
class MemoryOutStream : public std::ostringstream
{
public:
MemoryOutStream() {}
~MemoryOutStream() {}
char const* GetText() const;
private:
MemoryOutStream(MemoryOutStream const&);
void operator =(MemoryOutStream const&);
mutable std::string m_text;
};
}
#else
#include <cstddef>
namespace UnitTest
{
class MemoryOutStream
{
public:
explicit MemoryOutStream(int const size = 256);
~MemoryOutStream();
char const* GetText() const;
MemoryOutStream& operator << (char const* txt);
MemoryOutStream& operator << (int n);
MemoryOutStream& operator << (long n);
MemoryOutStream& operator << (unsigned long n);
MemoryOutStream& operator << (float f);
MemoryOutStream& operator << (double d);
MemoryOutStream& operator << (void const* p);
MemoryOutStream& operator << (unsigned int s);
enum { GROW_CHUNK_SIZE = 32 };
int GetCapacity() const;
private:
void operator= (MemoryOutStream const&);
void GrowBuffer(int capacity);
int m_capacity;
char* m_buffer;
};
}
#endif
#endif

View File

@ -1,57 +0,0 @@
#include "SignalTranslator.h"
namespace UnitTest {
#if defined(__native_client__)
SignalTranslator::SignalTranslator()
{
}
SignalTranslator::~SignalTranslator()
{
}
#else
sigjmp_buf* SignalTranslator::s_jumpTarget = 0;
namespace {
void SignalHandler(int sig)
{
siglongjmp(*SignalTranslator::s_jumpTarget, sig );
}
}
SignalTranslator::SignalTranslator()
{
m_oldJumpTarget = s_jumpTarget;
s_jumpTarget = &m_currentJumpTarget;
struct sigaction action;
action.sa_flags = 0;
action.sa_handler = SignalHandler;
sigemptyset( &action.sa_mask );
sigaction( SIGSEGV, &action, &m_old_SIGSEGV_action );
sigaction( SIGFPE , &action, &m_old_SIGFPE_action );
sigaction( SIGTRAP, &action, &m_old_SIGTRAP_action );
sigaction( SIGBUS , &action, &m_old_SIGBUS_action );
sigaction( SIGILL , &action, &m_old_SIGBUS_action );
}
SignalTranslator::~SignalTranslator()
{
sigaction( SIGILL , &m_old_SIGBUS_action , 0 );
sigaction( SIGBUS , &m_old_SIGBUS_action , 0 );
sigaction( SIGTRAP, &m_old_SIGTRAP_action, 0 );
sigaction( SIGFPE , &m_old_SIGFPE_action , 0 );
sigaction( SIGSEGV, &m_old_SIGSEGV_action, 0 );
s_jumpTarget = m_oldJumpTarget;
}
#endif // defined(__native_client__)
}

View File

@ -1,49 +0,0 @@
#ifndef UNITTEST_SIGNALTRANSLATOR_H
#define UNITTEST_SIGNALTRANSLATOR_H
#include <setjmp.h>
#include <signal.h>
namespace UnitTest {
class SignalTranslator
{
public:
SignalTranslator();
~SignalTranslator();
#if defined(__native_client__)
#else
static sigjmp_buf* s_jumpTarget;
private:
sigjmp_buf m_currentJumpTarget;
sigjmp_buf* m_oldJumpTarget;
struct sigaction m_old_SIGFPE_action;
struct sigaction m_old_SIGTRAP_action;
struct sigaction m_old_SIGSEGV_action;
struct sigaction m_old_SIGBUS_action;
// struct sigaction m_old_SIGABRT_action;
// struct sigaction m_old_SIGALRM_action;
#endif // defined(__native_client__)
};
#if !defined(__GNUC__) && !defined(__clang__)
# define UNITTEST_EXTENSION
#else
# define UNITTEST_EXTENSION __extension__
#endif
#if defined(__native_client__)
# define UNITTEST_THROW_SIGNALS
#else
# define UNITTEST_THROW_SIGNALS \
UnitTest::SignalTranslator sig; \
if (UNITTEST_EXTENSION sigsetjmp(*UnitTest::SignalTranslator::s_jumpTarget, 1) != 0) \
throw ("Unhandled system exception");
#endif // defined(__native_client__)
}
#endif

View File

@ -1,33 +0,0 @@
#include "TimeHelpers.h"
#include <unistd.h>
namespace UnitTest {
Timer::Timer()
{
m_startTime.tv_sec = 0;
m_startTime.tv_usec = 0;
}
void Timer::Start()
{
gettimeofday(&m_startTime, 0);
}
double Timer::GetTimeInMs() const
{
struct timeval currentTime;
gettimeofday(&currentTime, 0);
double const dsecs = currentTime.tv_sec - m_startTime.tv_sec;
double const dus = currentTime.tv_usec - m_startTime.tv_usec;
return (dsecs * 1000.0) + (dus / 1000.0);
}
void TimeHelpers::SleepMs(int ms)
{
usleep(ms * 1000);
}
}

View File

@ -1,28 +0,0 @@
#ifndef UNITTEST_TIMEHELPERS_H
#define UNITTEST_TIMEHELPERS_H
#include <sys/time.h>
namespace UnitTest {
class Timer
{
public:
Timer();
void Start();
double GetTimeInMs() const;
private:
struct timeval m_startTime;
};
namespace TimeHelpers
{
void SleepMs (int ms);
}
}
#endif

View File

@ -1,11 +0,0 @@
#include "ReportAssert.h"
#include "AssertException.h"
namespace UnitTest {
void ReportAssert(char const* description, char const* filename, int lineNumber)
{
throw AssertException(description, filename, lineNumber);
}
}

View File

@ -1,10 +0,0 @@
#ifndef UNITTEST_ASSERT_H
#define UNITTEST_ASSERT_H
namespace UnitTest {
void ReportAssert(char const* description, char const* filename, int lineNumber);
}
#endif

View File

@ -1,41 +0,0 @@
#include "Config.h"
#include "Test.h"
#include "TestList.h"
#include "TestResults.h"
#include "AssertException.h"
#include "MemoryOutStream.h"
#include "ExecuteTest.h"
#ifdef UNITTEST_POSIX
#include "Posix/SignalTranslator.h"
#endif
namespace UnitTest {
TestList& Test::GetTestList()
{
static TestList s_list;
return s_list;
}
Test::Test(char const* testName, char const* suiteName, char const* filename, int lineNumber)
: m_details(testName, suiteName, filename, lineNumber)
, next(0)
, m_timeConstraintExempt(false)
{
}
Test::~Test()
{
}
void Test::Run()
{
ExecuteTest(*this, m_details);
}
void Test::RunImpl() const
{
}
}

View File

@ -1,34 +0,0 @@
#ifndef UNITTEST_TEST_H
#define UNITTEST_TEST_H
#include "TestDetails.h"
namespace UnitTest {
class TestResults;
class TestList;
class Test
{
public:
explicit Test(char const* testName, char const* suiteName = "DefaultSuite", char const* filename = "", int lineNumber = 0);
virtual ~Test();
void Run();
TestDetails const m_details;
Test* next;
mutable bool m_timeConstraintExempt;
static TestList& GetTestList();
virtual void RunImpl() const;
private:
Test(Test const&);
Test& operator =(Test const&);
};
}
#endif

View File

@ -1,22 +0,0 @@
#include "TestDetails.h"
namespace UnitTest {
TestDetails::TestDetails(char const* testName_, char const* suiteName_, char const* filename_, int lineNumber_)
: suiteName(suiteName_)
, testName(testName_)
, filename(filename_)
, lineNumber(lineNumber_)
{
}
TestDetails::TestDetails(const TestDetails& details, int lineNumber_)
: suiteName(details.suiteName)
, testName(details.testName)
, filename(details.filename)
, lineNumber(lineNumber_)
{
}
}

View File

@ -1,24 +0,0 @@
#ifndef UNITTEST_TESTDETAILS_H
#define UNITTEST_TESTDETAILS_H
namespace UnitTest {
class TestDetails
{
public:
TestDetails(char const* testName, char const* suiteName, char const* filename, int lineNumber);
TestDetails(const TestDetails& details, int lineNumber);
char const* const suiteName;
char const* const testName;
char const* const filename;
int const lineNumber;
TestDetails(TestDetails const&); // Why is it public? --> http://gcc.gnu.org/bugs.html#cxx_rvalbind
private:
TestDetails& operator=(TestDetails const&);
};
}
#endif

View File

@ -1,39 +0,0 @@
#include "TestList.h"
#include "Test.h"
#include <cassert>
namespace UnitTest {
TestList::TestList()
: m_head(0)
, m_tail(0)
{
}
void TestList::Add(Test* test)
{
if (m_tail == 0)
{
assert(m_head == 0);
m_head = test;
m_tail = test;
}
else
{
m_tail->next = test;
m_tail = test;
}
}
Test* TestList::GetHead() const
{
return m_head;
}
ListAdder::ListAdder(TestList& list, Test* test)
{
list.Add(test);
}
}

View File

@ -1,32 +0,0 @@
#ifndef UNITTEST_TESTLIST_H
#define UNITTEST_TESTLIST_H
namespace UnitTest {
class Test;
class TestList
{
public:
TestList();
void Add (Test* test);
Test* GetHead() const;
private:
Test* m_head;
Test* m_tail;
};
class ListAdder
{
public:
ListAdder(TestList& list, Test* test);
};
}
#endif

View File

@ -1,113 +0,0 @@
#ifndef UNITTEST_TESTMACROS_H
#define UNITTEST_TESTMACROS_H
#include "Config.h"
#include "ExecuteTest.h"
#include "AssertException.h"
#include "TestDetails.h"
#include "MemoryOutStream.h"
#ifndef UNITTEST_POSIX
#define UNITTEST_THROW_SIGNALS
#else
#include "Posix/SignalTranslator.h"
#endif
#ifdef TEST
#error UnitTest++ redefines TEST
#endif
#ifdef TEST_EX
#error UnitTest++ redefines TEST_EX
#endif
#ifdef TEST_FIXTURE_EX
#error UnitTest++ redefines TEST_FIXTURE_EX
#endif
#define SUITE(Name) \
namespace Suite##Name { \
namespace UnitTestSuite { \
inline char const* GetSuiteName () { \
return #Name ; \
} \
} \
} \
namespace Suite##Name
#define TEST_EX(Name, List) \
class Test##Name : public UnitTest::Test \
{ \
public: \
Test##Name() : Test(#Name, UnitTestSuite::GetSuiteName(), __FILE__, __LINE__) {} \
private: \
virtual void RunImpl() const; \
} test##Name##Instance; \
\
UnitTest::ListAdder adder##Name (List, &test##Name##Instance); \
\
void Test##Name::RunImpl() const
#define TEST(Name) TEST_EX(Name, UnitTest::Test::GetTestList())
#define TEST_FIXTURE_EX(Fixture, Name, List) \
class Fixture##Name##Helper : public Fixture \
{ \
public: \
explicit Fixture##Name##Helper(UnitTest::TestDetails const& details) : m_details(details) {} \
void RunImpl(); \
UnitTest::TestDetails const& m_details; \
private: \
Fixture##Name##Helper(Fixture##Name##Helper const&); \
Fixture##Name##Helper& operator =(Fixture##Name##Helper const&); \
}; \
\
class Test##Fixture##Name : public UnitTest::Test \
{ \
public: \
Test##Fixture##Name() : Test(#Name, UnitTestSuite::GetSuiteName(), __FILE__, __LINE__) {} \
private: \
virtual void RunImpl() const; \
} test##Fixture##Name##Instance; \
\
UnitTest::ListAdder adder##Fixture##Name (List, &test##Fixture##Name##Instance); \
\
void Test##Fixture##Name::RunImpl() const \
{ \
bool ctorOk = false; \
try { \
Fixture##Name##Helper fixtureHelper(m_details); \
ctorOk = true; \
UnitTest::ExecuteTest(fixtureHelper, m_details); \
} \
catch (UnitTest::AssertException const& e) \
{ \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(m_details.testName, m_details.suiteName, e.Filename(), e.LineNumber()), e.what()); \
} \
catch (std::exception const& e) \
{ \
UnitTest::MemoryOutStream stream; \
stream << "Unhandled exception: " << e.what(); \
UnitTest::CurrentTest::Results()->OnTestFailure(m_details, stream.GetText()); \
} \
catch (...) { \
if (ctorOk) \
{ \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(m_details, __LINE__), \
"Unhandled exception while destroying fixture " #Fixture); \
} \
else \
{ \
UnitTest::CurrentTest::Results()->OnTestFailure(UnitTest::TestDetails(m_details, __LINE__), \
"Unhandled exception while constructing fixture " #Fixture); \
} \
} \
} \
void Fixture##Name##Helper::RunImpl()
#define TEST_FIXTURE(Fixture,Name) TEST_FIXTURE_EX(Fixture, Name, UnitTest::Test::GetTestList())
#endif

View File

@ -1,10 +0,0 @@
#include "TestReporter.h"
namespace UnitTest {
TestReporter::~TestReporter()
{
}
}

View File

@ -1,20 +0,0 @@
#ifndef UNITTEST_TESTREPORTER_H
#define UNITTEST_TESTREPORTER_H
namespace UnitTest {
class TestDetails;
class TestReporter
{
public:
virtual ~TestReporter();
virtual void ReportTestStart(TestDetails const& test) = 0;
virtual void ReportFailure(TestDetails const& test, char const* failure) = 0;
virtual void ReportTestFinish(TestDetails const& test, float secondsElapsed) = 0;
virtual void ReportSummary(int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed) = 0;
};
}
#endif

View File

@ -1,57 +0,0 @@
#include "TestReporterStdout.h"
#include <cstdio>
#include "TestDetails.h"
// cstdio doesn't pull in namespace std on VC6, so we do it here.
#if defined(_MSC_VER) && (_MSC_VER == 1200)
namespace std {}
#endif
#if defined(__ANDROID__)
# include <android/log.h>
# define outf(format, ...) __android_log_print(ANDROID_LOG_DEBUG, "", format, ##__VA_ARGS__)
#else
# define outf(format, ...) printf(format, ##__VA_ARGS__)
#endif // defined(__ANDROID__)
namespace UnitTest {
void TestReporterStdout::ReportFailure(TestDetails const& details, char const* failure)
{
#if defined(__APPLE__) || defined(__GNUG__)
char const* const errorFormat = "%s:%d: error: Failure in %s: %s\n";
#else
char const* const errorFormat = "%s(%d): error: Failure in %s: %s\n";
#endif
using namespace std;
outf(errorFormat, details.filename, details.lineNumber, details.testName, failure);
}
void TestReporterStdout::ReportTestStart(TestDetails const& /*test*/)
{
}
void TestReporterStdout::ReportTestFinish(TestDetails const& /*test*/, float)
{
}
void TestReporterStdout::ReportSummary(int const totalTestCount, int const failedTestCount,
int const failureCount, float secondsElapsed)
{
using namespace std;
if (failureCount > 0)
{
outf("FAILURE: %d out of %d tests failed (%d failures).\n", failedTestCount, totalTestCount, failureCount);
}
else
{
outf("Success: %d tests passed.\n", totalTestCount);
}
outf("Test time: %.2f seconds.\n", secondsElapsed);
}
}

View File

@ -1,19 +0,0 @@
#ifndef UNITTEST_TESTREPORTERSTDOUT_H
#define UNITTEST_TESTREPORTERSTDOUT_H
#include "TestReporter.h"
namespace UnitTest {
class TestReporterStdout : public TestReporter
{
private:
virtual void ReportTestStart(TestDetails const& test);
virtual void ReportFailure(TestDetails const& test, char const* failure);
virtual void ReportTestFinish(TestDetails const& test, float secondsElapsed);
virtual void ReportSummary(int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed);
};
}
#endif

View File

@ -1,60 +0,0 @@
#include "TestResults.h"
#include "TestReporter.h"
#include "TestDetails.h"
namespace UnitTest {
TestResults::TestResults(TestReporter* testReporter)
: m_testReporter(testReporter)
, m_totalTestCount(0)
, m_failedTestCount(0)
, m_failureCount(0)
, m_currentTestFailed(false)
{
}
void TestResults::OnTestStart(TestDetails const& test)
{
++m_totalTestCount;
m_currentTestFailed = false;
if (m_testReporter)
m_testReporter->ReportTestStart(test);
}
void TestResults::OnTestFailure(TestDetails const& test, char const* failure)
{
++m_failureCount;
if (!m_currentTestFailed)
{
++m_failedTestCount;
m_currentTestFailed = true;
}
if (m_testReporter)
m_testReporter->ReportFailure(test, failure);
}
void TestResults::OnTestFinish(TestDetails const& test, float secondsElapsed)
{
if (m_testReporter)
m_testReporter->ReportTestFinish(test, secondsElapsed);
}
int TestResults::GetTotalTestCount() const
{
return m_totalTestCount;
}
int TestResults::GetFailedTestCount() const
{
return m_failedTestCount;
}
int TestResults::GetFailureCount() const
{
return m_failureCount;
}
}

View File

@ -1,36 +0,0 @@
#ifndef UNITTEST_TESTRESULTS_H
#define UNITTEST_TESTRESULTS_H
namespace UnitTest {
class TestReporter;
class TestDetails;
class TestResults
{
public:
explicit TestResults(TestReporter* reporter = 0);
void OnTestStart(TestDetails const& test);
void OnTestFailure(TestDetails const& test, char const* failure);
void OnTestFinish(TestDetails const& test, float secondsElapsed);
int GetTotalTestCount() const;
int GetFailedTestCount() const;
int GetFailureCount() const;
private:
TestReporter* m_testReporter;
int m_totalTestCount;
int m_failedTestCount;
int m_failureCount;
bool m_currentTestFailed;
TestResults(TestResults const&);
TestResults& operator =(TestResults const&);
};
}
#endif

View File

@ -1,76 +0,0 @@
#include "TestRunner.h"
#include "TestResults.h"
#include "TestReporter.h"
#include "TestReporterStdout.h"
#include "TimeHelpers.h"
#include "MemoryOutStream.h"
#include <cstring>
namespace UnitTest {
int RunAllTests()
{
TestReporterStdout reporter;
TestRunner runner(reporter);
return runner.RunTestsIf(Test::GetTestList(), NULL, True(), 0);
}
TestRunner::TestRunner(TestReporter& reporter)
: m_reporter(&reporter)
, m_result(new TestResults(&reporter))
, m_timer(new Timer)
{
m_timer->Start();
}
TestRunner::~TestRunner()
{
delete m_result;
delete m_timer;
}
int TestRunner::Finish() const
{
float const secondsElapsed = static_cast<float>(m_timer->GetTimeInMs() / 1000.0);
m_reporter->ReportSummary(m_result->GetTotalTestCount(),
m_result->GetFailedTestCount(),
m_result->GetFailureCount(),
secondsElapsed);
return m_result->GetFailureCount();
}
bool TestRunner::IsTestInSuite(const Test* const curTest, char const* suiteName) const
{
using namespace std;
return (suiteName == NULL) || !strcmp(curTest->m_details.suiteName, suiteName);
}
void TestRunner::RunTest(TestResults* const result, Test* const curTest, int const maxTestTimeInMs) const
{
CurrentTest::Results() = result;
Timer testTimer;
testTimer.Start();
result->OnTestStart(curTest->m_details);
curTest->Run();
double const testTimeInMs = testTimer.GetTimeInMs();
if (maxTestTimeInMs > 0 && testTimeInMs > maxTestTimeInMs && !curTest->m_timeConstraintExempt)
{
MemoryOutStream stream;
stream << "Global time constraint failed. Expected under " << maxTestTimeInMs <<
"ms but took " << testTimeInMs << "ms.";
result->OnTestFailure(curTest->m_details, stream.GetText());
}
result->OnTestFinish(curTest->m_details, static_cast<float>(testTimeInMs/1000.0));
}
}

View File

@ -1,59 +0,0 @@
#ifndef UNITTEST_TESTRUNNER_H
#define UNITTEST_TESTRUNNER_H
#include "Test.h"
#include "TestList.h"
#include "CurrentTest.h"
namespace UnitTest {
class TestReporter;
class TestResults;
class Timer;
int RunAllTests();
struct True
{
bool operator()(const Test* const) const
{
return true;
}
};
class TestRunner
{
public:
explicit TestRunner(TestReporter& reporter);
~TestRunner();
template <class Predicate>
int RunTestsIf(TestList const& list, char const* suiteName,
const Predicate& predicate, int maxTestTimeInMs) const
{
Test* curTest = list.GetHead();
while (curTest != 0)
{
if (IsTestInSuite(curTest, suiteName) && predicate(curTest))
RunTest(m_result, curTest, maxTestTimeInMs);
curTest = curTest->next;
}
return Finish();
}
private:
TestReporter* m_reporter;
TestResults* m_result;
Timer* m_timer;
int Finish() const;
bool IsTestInSuite(const Test* const curTest, char const* suiteName) const;
void RunTest(TestResults* const result, Test* const curTest, int const maxTestTimeInMs) const;
};
}
#endif

View File

@ -1,12 +0,0 @@
#ifndef UNITTEST_TESTSUITE_H
#define UNITTEST_TESTSUITE_H
namespace UnitTestSuite
{
inline char const* GetSuiteName ()
{
return "DefaultSuite";
}
}
#endif

View File

@ -1,29 +0,0 @@
#include "TimeConstraint.h"
#include "TestResults.h"
#include "MemoryOutStream.h"
#include "CurrentTest.h"
namespace UnitTest {
TimeConstraint::TimeConstraint(int ms, TestDetails const& details)
: m_details(details)
, m_maxMs(ms)
{
m_timer.Start();
}
TimeConstraint::~TimeConstraint()
{
double const totalTimeInMs = m_timer.GetTimeInMs();
if (totalTimeInMs > m_maxMs)
{
MemoryOutStream stream;
stream << "Time constraint failed. Expected to run test under " << m_maxMs <<
"ms but took " << totalTimeInMs << "ms.";
UnitTest::CurrentTest::Results()->OnTestFailure(m_details, stream.GetText());
}
}
}

View File

@ -1,33 +0,0 @@
#ifndef UNITTEST_TIMECONSTRAINT_H
#define UNITTEST_TIMECONSTRAINT_H
#include "TimeHelpers.h"
namespace UnitTest {
class TestResults;
class TestDetails;
class TimeConstraint
{
public:
TimeConstraint(int ms, TestDetails const& details);
~TimeConstraint();
private:
void operator=(TimeConstraint const&);
TimeConstraint(TimeConstraint const&);
Timer m_timer;
TestDetails const& m_details;
int const m_maxMs;
};
#define UNITTEST_TIME_CONSTRAINT(ms) \
UnitTest::TimeConstraint unitTest__timeConstraint__(ms, UnitTest::TestDetails(m_details, __LINE__))
#define UNITTEST_TIME_CONSTRAINT_EXEMPT() do { m_timeConstraintExempt = true; } while (0)
}
#endif

View File

@ -1,7 +0,0 @@
#include "Config.h"
#if defined UNITTEST_POSIX
#include "Posix/TimeHelpers.h"
#else
#include "Win32/TimeHelpers.h"
#endif

View File

@ -1,18 +0,0 @@
#ifndef UNITTESTCPP_H
#define UNITTESTCPP_H
//lint -esym(1509,*Fixture)
#include "Config.h"
#include "Test.h"
#include "TestList.h"
#include "TestSuite.h"
#include "TestResults.h"
#include "TestMacros.h"
#include "CheckMacros.h"
#include "TestRunner.h"
#include "TimeConstraint.h"
#endif

View File

@ -1,47 +0,0 @@
#include "TimeHelpers.h"
#include <windows.h>
namespace UnitTest {
Timer::Timer()
: m_threadHandle(::GetCurrentThread())
, m_startTime(0)
{
#if defined(_MSC_VER) && (_MSC_VER == 1200) // VC6 doesn't have DWORD_PTR?
typedef unsigned long DWORD_PTR;
#endif
DWORD_PTR systemMask;
::GetProcessAffinityMask(GetCurrentProcess(), &m_processAffinityMask, &systemMask);
::SetThreadAffinityMask(m_threadHandle, 1);
::QueryPerformanceFrequency(reinterpret_cast< LARGE_INTEGER* >(&m_frequency));
::SetThreadAffinityMask(m_threadHandle, m_processAffinityMask);
}
void Timer::Start()
{
m_startTime = GetTime();
}
double Timer::GetTimeInMs() const
{
__int64 const elapsedTime = GetTime() - m_startTime;
double const seconds = double(elapsedTime) / double(m_frequency);
return seconds * 1000.0;
}
__int64 Timer::GetTime() const
{
LARGE_INTEGER curTime;
::SetThreadAffinityMask(m_threadHandle, 1);
::QueryPerformanceCounter(&curTime);
::SetThreadAffinityMask(m_threadHandle, m_processAffinityMask);
return curTime.QuadPart;
}
void TimeHelpers::SleepMs(int const ms)
{
::Sleep(ms);
}
}

View File

@ -1,48 +0,0 @@
#ifndef UNITTEST_TIMEHELPERS_H
#define UNITTEST_TIMEHELPERS_H
#include "../Config.h"
#ifdef UNITTEST_MINGW
#ifndef __int64
#define __int64 long long
#endif
#endif
namespace UnitTest {
class Timer
{
public:
Timer();
void Start();
double GetTimeInMs() const;
private:
__int64 GetTime() const;
void* m_threadHandle;
#if defined(_WIN64)
unsigned __int64 m_processAffinityMask;
#else
unsigned long m_processAffinityMask;
#endif
__int64 m_startTime;
__int64 m_frequency;
};
namespace TimeHelpers
{
void SleepMs (int ms);
}
}
#endif

View File

@ -1,127 +0,0 @@
#include "XmlTestReporter.h"
#include "Config.h"
#include <iostream>
#include <sstream>
#include <string>
using std::string;
using std::ostringstream;
using std::ostream;
namespace {
void ReplaceChar(string& str, char c, string const& replacement)
{
for (size_t pos = str.find(c); pos != string::npos; pos = str.find(c, pos + 1))
str.replace(pos, 1, replacement);
}
string XmlEscape(string const& value)
{
string escaped = value;
ReplaceChar(escaped, '&', "&amp;");
ReplaceChar(escaped, '<', "&lt;");
ReplaceChar(escaped, '>', "&gt;");
ReplaceChar(escaped, '\'', "&apos;");
ReplaceChar(escaped, '\"', "&quot;");
return escaped;
}
string BuildFailureMessage(string const& file, int line, string const& message)
{
ostringstream failureMessage;
failureMessage << file << "(" << line << ") : " << message;
return failureMessage.str();
}
}
namespace UnitTest {
XmlTestReporter::XmlTestReporter(ostream& ostream)
: m_ostream(ostream)
{
}
void XmlTestReporter::ReportSummary(int totalTestCount, int failedTestCount,
int failureCount, float secondsElapsed)
{
AddXmlElement(m_ostream, NULL);
BeginResults(m_ostream, totalTestCount, failedTestCount, failureCount, secondsElapsed);
DeferredTestResultList const& results = GetResults();
for (DeferredTestResultList::const_iterator i = results.begin(); i != results.end(); ++i)
{
BeginTest(m_ostream, *i);
if (i->failed)
AddFailure(m_ostream, *i);
EndTest(m_ostream, *i);
}
EndResults(m_ostream);
}
void XmlTestReporter::AddXmlElement(ostream& os, char const* encoding)
{
os << "<?xml version=\"1.0\"";
if (encoding != NULL)
os << " encoding=\"" << encoding << "\"";
os << "?>";
}
void XmlTestReporter::BeginResults(std::ostream& os, int totalTestCount, int failedTestCount,
int failureCount, float secondsElapsed)
{
os << "<unittest-results"
<< " tests=\"" << totalTestCount << "\""
<< " failedtests=\"" << failedTestCount << "\""
<< " failures=\"" << failureCount << "\""
<< " time=\"" << secondsElapsed << "\""
<< ">";
}
void XmlTestReporter::EndResults(std::ostream& os)
{
os << "</unittest-results>";
}
void XmlTestReporter::BeginTest(std::ostream& os, DeferredTestResult const& result)
{
os << "<test"
<< " suite=\"" << result.suiteName << "\""
<< " name=\"" << result.testName << "\""
<< " time=\"" << result.timeElapsed << "\"";
}
void XmlTestReporter::EndTest(std::ostream& os, DeferredTestResult const& result)
{
if (result.failed)
os << "</test>";
else
os << "/>";
}
void XmlTestReporter::AddFailure(std::ostream& os, DeferredTestResult const& result)
{
os << ">"; // close <test> element
for (DeferredTestResult::FailureVec::const_iterator it = result.failures.begin();
it != result.failures.end();
++it)
{
string const escapedMessage = XmlEscape(it->second);
string const message = BuildFailureMessage(result.failureFile, it->first, escapedMessage);
os << "<failure" << " message=\"" << message << "\"" << "/>";
}
}
}

View File

@ -1,34 +0,0 @@
#ifndef UNITTEST_XMLTESTREPORTER_H
#define UNITTEST_XMLTESTREPORTER_H
#include "DeferredTestReporter.h"
#include <iosfwd>
namespace UnitTest
{
class XmlTestReporter : public DeferredTestReporter
{
public:
explicit XmlTestReporter(std::ostream& ostream);
virtual void ReportSummary(int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed);
private:
XmlTestReporter(XmlTestReporter const&);
XmlTestReporter& operator=(XmlTestReporter const&);
void AddXmlElement(std::ostream& os, char const* encoding);
void BeginResults(std::ostream& os, int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed);
void EndResults(std::ostream& os);
void BeginTest(std::ostream& os, DeferredTestResult const& result);
void AddFailure(std::ostream& os, DeferredTestResult const& result);
void EndTest(std::ostream& os, DeferredTestResult const& result);
std::ostream& m_ostream;
};
}
#endif

View File

@ -1,8 +0,0 @@
#include "../UnitTest++.h"
#include "../TestReporterStdout.h"
int main(int, char const *[])
{
return UnitTest::RunAllTests();
}

View File

@ -1,98 +0,0 @@
#ifndef UNITTEST_RECORDINGREPORTER_H
#define UNITTEST_RECORDINGREPORTER_H
#include "../TestReporter.h"
#include <cstring>
#include "../TestDetails.h"
struct RecordingReporter : public UnitTest::TestReporter
{
private:
enum { kMaxStringLength = 256 };
public:
RecordingReporter()
: testRunCount(0)
, testFailedCount(0)
, lastFailedLine(0)
, testFinishedCount(0)
, lastFinishedTestTime(0)
, summaryTotalTestCount(0)
, summaryFailedTestCount(0)
, summaryFailureCount(0)
, summarySecondsElapsed(0)
{
lastStartedSuite[0] = '\0';
lastStartedTest[0] = '\0';
lastFailedFile[0] = '\0';
lastFailedSuite[0] = '\0';
lastFailedTest[0] = '\0';
lastFailedMessage[0] = '\0';
lastFinishedSuite[0] = '\0';
lastFinishedTest[0] = '\0';
}
virtual void ReportTestStart(UnitTest::TestDetails const& test)
{
using namespace std;
++testRunCount;
strcpy(lastStartedSuite, test.suiteName);
strcpy(lastStartedTest, test.testName);
}
virtual void ReportFailure(UnitTest::TestDetails const& test, char const* failure)
{
using namespace std;
++testFailedCount;
strcpy(lastFailedFile, test.filename);
lastFailedLine = test.lineNumber;
strcpy(lastFailedSuite, test.suiteName);
strcpy(lastFailedTest, test.testName);
strcpy(lastFailedMessage, failure);
}
virtual void ReportTestFinish(UnitTest::TestDetails const& test, float testDuration)
{
using namespace std;
++testFinishedCount;
strcpy(lastFinishedSuite, test.suiteName);
strcpy(lastFinishedTest, test.testName);
lastFinishedTestTime = testDuration;
}
virtual void ReportSummary(int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed)
{
summaryTotalTestCount = totalTestCount;
summaryFailedTestCount = failedTestCount;
summaryFailureCount = failureCount;
summarySecondsElapsed = secondsElapsed;
}
int testRunCount;
char lastStartedSuite[kMaxStringLength];
char lastStartedTest[kMaxStringLength];
int testFailedCount;
char lastFailedFile[kMaxStringLength];
int lastFailedLine;
char lastFailedSuite[kMaxStringLength];
char lastFailedTest[kMaxStringLength];
char lastFailedMessage[kMaxStringLength];
int testFinishedCount;
char lastFinishedSuite[kMaxStringLength];
char lastFinishedTest[kMaxStringLength];
float lastFinishedTestTime;
int summaryTotalTestCount;
int summaryFailedTestCount;
int summaryFailureCount;
float summarySecondsElapsed;
};
#endif

View File

@ -1,37 +0,0 @@
#ifndef UNITTEST_SCOPEDCURRENTTEST_H
#define UNITTEST_SCOPEDCURRENTTEST_H
#include "../CurrentTest.h"
#include <cstddef>
class ScopedCurrentTest
{
public:
ScopedCurrentTest()
: m_oldTestResults(UnitTest::CurrentTest::Results())
, m_oldTestDetails(UnitTest::CurrentTest::Details())
{
}
explicit ScopedCurrentTest(UnitTest::TestResults& newResults, const UnitTest::TestDetails* newDetails = NULL)
: m_oldTestResults(UnitTest::CurrentTest::Results())
, m_oldTestDetails(UnitTest::CurrentTest::Details())
{
UnitTest::CurrentTest::Results() = &newResults;
if (newDetails != NULL)
UnitTest::CurrentTest::Details() = newDetails;
}
~ScopedCurrentTest()
{
UnitTest::CurrentTest::Results() = m_oldTestResults;
UnitTest::CurrentTest::Details() = m_oldTestDetails;
}
private:
UnitTest::TestResults* m_oldTestResults;
const UnitTest::TestDetails* m_oldTestDetails;
};
#endif

View File

@ -1,44 +0,0 @@
#include "../UnitTest++.h"
#include "../AssertException.h"
#include "../ReportAssert.h"
using namespace UnitTest;
namespace {
TEST(ReportAssertThrowsAssertException)
{
bool caught = false;
try
{
ReportAssert("", "", 0);
}
catch(AssertException const&)
{
caught = true;
}
CHECK (true == caught);
}
TEST(ReportAssertSetsCorrectInfoInException)
{
const int lineNumber = 12345;
const char* description = "description";
const char* filename = "filename";
try
{
ReportAssert(description, filename, lineNumber);
}
catch(AssertException const& e)
{
CHECK_EQUAL(description, e.what());
CHECK_EQUAL(filename, e.Filename());
CHECK_EQUAL(lineNumber, e.LineNumber());
}
}
}

View File

@ -1,801 +0,0 @@
#include "../UnitTest++.h"
#include "../CurrentTest.h"
#include "RecordingReporter.h"
#include "ScopedCurrentTest.h"
using namespace std;
namespace {
TEST(CheckSucceedsOnTrue)
{
bool failure = true;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK(true);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(!failure);
}
TEST(CheckFailsOnFalse)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK(false);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(FailureReportsCorrectTestName)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK(false);
}
CHECK_EQUAL(m_details.testName, reporter.lastFailedTest);
}
TEST(CheckFailureIncludesCheckContents)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const bool yaddayadda = false;
CHECK(yaddayadda);
}
CHECK(strstr(reporter.lastFailedMessage, "yaddayadda"));
}
int ThrowingFunction()
{
throw "Doh";
}
TEST(CheckFailsOnException)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK(ThrowingFunction() == 1);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckFailureBecauseOfExceptionIncludesCheckContents)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK(ThrowingFunction() == 1);
}
CHECK(strstr(reporter.lastFailedMessage, "ThrowingFunction() == 1"));
}
TEST(CheckEqualSucceedsOnEqual)
{
bool failure = true;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK_EQUAL(1, 1);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(!failure);
}
TEST(CheckEqualFailsOnNotEqual)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK_EQUAL(1, 2);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckEqualFailsOnException)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK_EQUAL(ThrowingFunction(), 1);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckEqualFailureContainsCorrectDetails)
{
int line = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
UnitTest::TestDetails const testDetails("testName", "suiteName", "filename", -1);
ScopedCurrentTest scopedResults(testResults, &testDetails);
CHECK_EQUAL(1, 123); line = __LINE__;
}
CHECK_EQUAL("testName", reporter.lastFailedTest);
CHECK_EQUAL("suiteName", reporter.lastFailedSuite);
CHECK_EQUAL("filename", reporter.lastFailedFile);
CHECK_EQUAL(line, reporter.lastFailedLine);
}
TEST(CheckEqualFailureBecauseOfExceptionContainsCorrectDetails)
{
int line = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
UnitTest::TestDetails const testDetails("testName", "suiteName", "filename", -1);
ScopedCurrentTest scopedResults(testResults, &testDetails);
CHECK_EQUAL(ThrowingFunction(), 123); line = __LINE__;
}
CHECK_EQUAL("testName", reporter.lastFailedTest);
CHECK_EQUAL("suiteName", reporter.lastFailedSuite);
CHECK_EQUAL("filename", reporter.lastFailedFile);
CHECK_EQUAL(line, reporter.lastFailedLine);
}
TEST(CheckEqualFailureBecauseOfExceptionIncludesCheckContents)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK_EQUAL(ThrowingFunction(), 123);
}
CHECK(strstr(reporter.lastFailedMessage, "ThrowingFunction()"));
CHECK(strstr(reporter.lastFailedMessage, "123"));
}
int g_sideEffect = 0;
int FunctionWithSideEffects()
{
++g_sideEffect;
return 1;
}
TEST(CheckEqualDoesNotHaveSideEffectsWhenPassing)
{
g_sideEffect = 0;
{
UnitTest::TestResults testResults;
ScopedCurrentTest scopedResults(testResults);
CHECK_EQUAL(1, FunctionWithSideEffects());
}
CHECK_EQUAL(1, g_sideEffect);
}
TEST(CheckEqualDoesNotHaveSideEffectsWhenFailing)
{
g_sideEffect = 0;
{
UnitTest::TestResults testResults;
ScopedCurrentTest scopedResults(testResults);
CHECK_EQUAL(2, FunctionWithSideEffects());
}
CHECK_EQUAL(1, g_sideEffect);
}
TEST(CheckCloseSucceedsOnEqual)
{
bool failure = true;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK_CLOSE (1.0f, 1.001f, 0.01f);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(!failure);
}
TEST(CheckCloseFailsOnNotEqual)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK_CLOSE (1.0f, 1.1f, 0.01f);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckCloseFailsOnException)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK_CLOSE ((float)ThrowingFunction(), 1.0001f, 0.1f);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckCloseFailureContainsCorrectDetails)
{
int line = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
UnitTest::TestDetails testDetails("test", "suite", "filename", -1);
ScopedCurrentTest scopedResults(testResults, &testDetails);
CHECK_CLOSE (1.0f, 1.1f, 0.01f); line = __LINE__;
}
CHECK_EQUAL("test", reporter.lastFailedTest);
CHECK_EQUAL("suite", reporter.lastFailedSuite);
CHECK_EQUAL("filename", reporter.lastFailedFile);
CHECK_EQUAL(line, reporter.lastFailedLine);
}
TEST(CheckCloseFailureBecauseOfExceptionContainsCorrectDetails)
{
int line = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
UnitTest::TestDetails testDetails("closeTest", "closeSuite", "filename", -1);
ScopedCurrentTest scopedResults(testResults, &testDetails);
CHECK_CLOSE ((float)ThrowingFunction(), 1.0001f, 0.1f); line = __LINE__;
}
CHECK_EQUAL("closeTest", reporter.lastFailedTest);
CHECK_EQUAL("closeSuite", reporter.lastFailedSuite);
CHECK_EQUAL("filename", reporter.lastFailedFile);
CHECK_EQUAL(line, reporter.lastFailedLine);
}
TEST(CheckCloseFailureBecauseOfExceptionIncludesCheckContents)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
CHECK_CLOSE ((float)ThrowingFunction(), 1.0001f, 0.1f);
}
CHECK(strstr(reporter.lastFailedMessage, "(float)ThrowingFunction()"));
CHECK(strstr(reporter.lastFailedMessage, "1.0001f"));
}
TEST(CheckCloseDoesNotHaveSideEffectsWhenPassing)
{
g_sideEffect = 0;
{
UnitTest::TestResults testResults;
ScopedCurrentTest scopedResults(testResults);
CHECK_CLOSE (1, FunctionWithSideEffects(), 0.1f);
}
CHECK_EQUAL(1, g_sideEffect);
}
TEST(CheckCloseDoesNotHaveSideEffectsWhenFailing)
{
g_sideEffect = 0;
{
UnitTest::TestResults testResults;
ScopedCurrentTest scopedResults(testResults);
CHECK_CLOSE (2, FunctionWithSideEffects(), 0.1f);
}
CHECK_EQUAL(1, g_sideEffect);
}
class ThrowingObject
{
public:
float operator[](int) const
{
throw "Test throw";
}
};
TEST(CheckArrayCloseSucceedsOnEqual)
{
bool failure = true;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const float data[4] = { 0, 1, 2, 3 };
CHECK_ARRAY_CLOSE (data, data, 4, 0.01f);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(!failure);
}
TEST(CheckArrayCloseFailsOnNotEqual)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
int const data1[4] = { 0, 1, 2, 3 };
int const data2[4] = { 0, 1, 3, 3 };
CHECK_ARRAY_CLOSE (data1, data2, 4, 0.01f);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckArrayCloseFailureIncludesCheckExpectedAndActual)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
int const data1[4] = { 0, 1, 2, 3 };
int const data2[4] = { 0, 1, 3, 3 };
CHECK_ARRAY_CLOSE (data1, data2, 4, 0.01f);
}
CHECK(strstr(reporter.lastFailedMessage, "xpected [ 0 1 2 3 ]"));
CHECK(strstr(reporter.lastFailedMessage, "was [ 0 1 3 3 ]"));
}
TEST(CheckArrayCloseFailureContainsCorrectDetails)
{
int line = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
UnitTest::TestDetails testDetails("arrayCloseTest", "arrayCloseSuite", "filename", -1);
ScopedCurrentTest scopedResults(testResults, &testDetails);
int const data1[4] = { 0, 1, 2, 3 };
int const data2[4] = { 0, 1, 3, 3 };
CHECK_ARRAY_CLOSE (data1, data2, 4, 0.01f); line = __LINE__;
}
CHECK_EQUAL("arrayCloseTest", reporter.lastFailedTest);
CHECK_EQUAL("arrayCloseSuite", reporter.lastFailedSuite);
CHECK_EQUAL("filename", reporter.lastFailedFile);
CHECK_EQUAL(line, reporter.lastFailedLine);
}
TEST(CheckArrayCloseFailureBecauseOfExceptionContainsCorrectDetails)
{
int line = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
UnitTest::TestDetails testDetails("arrayCloseTest", "arrayCloseSuite", "filename", -1);
ScopedCurrentTest scopedResults(testResults, &testDetails);
int const data[4] = { 0, 1, 2, 3 };
CHECK_ARRAY_CLOSE (data, ThrowingObject(), 4, 0.01f); line = __LINE__;
}
CHECK_EQUAL("arrayCloseTest", reporter.lastFailedTest);
CHECK_EQUAL("arrayCloseSuite", reporter.lastFailedSuite);
CHECK_EQUAL("filename", reporter.lastFailedFile);
CHECK_EQUAL(line, reporter.lastFailedLine);
}
TEST(CheckArrayCloseFailureIncludesTolerance)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
float const data1[4] = { 0, 1, 2, 3 };
float const data2[4] = { 0, 1, 3, 3 };
CHECK_ARRAY_CLOSE (data1, data2, 4, 0.01f);
}
CHECK(strstr(reporter.lastFailedMessage, "0.01"));
}
TEST(CheckArrayCloseFailsOnException)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const float data[4] = { 0, 1, 2, 3 };
ThrowingObject obj;
CHECK_ARRAY_CLOSE (data, obj, 3, 0.01f);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckArrayCloseFailureOnExceptionIncludesCheckContents)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const float data[4] = { 0, 1, 2, 3 };
ThrowingObject obj;
CHECK_ARRAY_CLOSE (data, obj, 3, 0.01f);
}
CHECK(strstr(reporter.lastFailedMessage, "data"));
CHECK(strstr(reporter.lastFailedMessage, "obj"));
}
TEST(CheckArrayEqualSuceedsOnEqual)
{
bool failure = true;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const float data[4] = { 0, 1, 2, 3 };
CHECK_ARRAY_EQUAL (data, data, 4);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(!failure);
}
TEST(CheckArrayEqualFailsOnNotEqual)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
int const data1[4] = { 0, 1, 2, 3 };
int const data2[4] = { 0, 1, 3, 3 };
CHECK_ARRAY_EQUAL (data1, data2, 4);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckArrayEqualFailureIncludesCheckExpectedAndActual)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
int const data1[4] = { 0, 1, 2, 3 };
int const data2[4] = { 0, 1, 3, 3 };
CHECK_ARRAY_EQUAL (data1, data2, 4);
}
CHECK(strstr(reporter.lastFailedMessage, "xpected [ 0 1 2 3 ]"));
CHECK(strstr(reporter.lastFailedMessage, "was [ 0 1 3 3 ]"));
}
TEST(CheckArrayEqualFailureContainsCorrectInfo)
{
int line = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
int const data1[4] = { 0, 1, 2, 3 };
int const data2[4] = { 0, 1, 3, 3 };
CHECK_ARRAY_EQUAL (data1, data2, 4); line = __LINE__;
}
CHECK_EQUAL("CheckArrayEqualFailureContainsCorrectInfo", reporter.lastFailedTest);
CHECK_EQUAL(__FILE__, reporter.lastFailedFile);
CHECK_EQUAL(line, reporter.lastFailedLine);
}
TEST(CheckArrayEqualFailsOnException)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const float data[4] = { 0, 1, 2, 3 };
ThrowingObject obj;
CHECK_ARRAY_EQUAL (data, obj, 3);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckArrayEqualFailureOnExceptionIncludesCheckContents)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const float data[4] = { 0, 1, 2, 3 };
ThrowingObject obj;
CHECK_ARRAY_EQUAL (data, obj, 3);
}
CHECK(strstr(reporter.lastFailedMessage, "data"));
CHECK(strstr(reporter.lastFailedMessage, "obj"));
}
float const* FunctionWithSideEffects2()
{
++g_sideEffect;
static float const data[] = {1,2,3,4};
return data;
}
TEST(CheckArrayCloseDoesNotHaveSideEffectsWhenPassing)
{
g_sideEffect = 0;
{
UnitTest::TestResults testResults;
ScopedCurrentTest scopedResults(testResults);
const float data[] = { 0, 1, 2, 3 };
CHECK_ARRAY_CLOSE (data, FunctionWithSideEffects2(), 4, 0.01f);
}
CHECK_EQUAL(1, g_sideEffect);
}
TEST(CheckArrayCloseDoesNotHaveSideEffectsWhenFailing)
{
g_sideEffect = 0;
{
UnitTest::TestResults testResults;
ScopedCurrentTest scopedResults(testResults);
const float data[] = { 0, 1, 3, 3 };
CHECK_ARRAY_CLOSE (data, FunctionWithSideEffects2(), 4, 0.01f);
}
CHECK_EQUAL(1, g_sideEffect);
}
class ThrowingObject2D
{
public:
float* operator[](int) const
{
throw "Test throw";
}
};
TEST(CheckArray2DCloseSucceedsOnEqual)
{
bool failure = true;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const float data[2][2] = { {0, 1}, {2, 3} };
CHECK_ARRAY2D_CLOSE (data, data, 2, 2, 0.01f);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(!failure);
}
TEST(CheckArray2DCloseFailsOnNotEqual)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
int const data1[2][2] = { {0, 1}, {2, 3} };
int const data2[2][2] = { {0, 1}, {3, 3} };
CHECK_ARRAY2D_CLOSE (data1, data2, 2, 2, 0.01f);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckArray2DCloseFailureIncludesCheckExpectedAndActual)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
int const data1[2][2] = { {0, 1}, {2, 3} };
int const data2[2][2] = { {0, 1}, {3, 3} };
CHECK_ARRAY2D_CLOSE (data1, data2, 2, 2, 0.01f);
}
CHECK(strstr(reporter.lastFailedMessage, "xpected [ [ 0 1 ] [ 2 3 ] ]"));
CHECK(strstr(reporter.lastFailedMessage, "was [ [ 0 1 ] [ 3 3 ] ]"));
}
TEST(CheckArray2DCloseFailureContainsCorrectDetails)
{
int line = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
UnitTest::TestDetails testDetails("array2DCloseTest", "array2DCloseSuite", "filename", -1);
ScopedCurrentTest scopedResults(testResults, &testDetails);
int const data1[2][2] = { {0, 1}, {2, 3} };
int const data2[2][2] = { {0, 1}, {3, 3} };
CHECK_ARRAY2D_CLOSE (data1, data2, 2, 2, 0.01f); line = __LINE__;
}
CHECK_EQUAL("array2DCloseTest", reporter.lastFailedTest);
CHECK_EQUAL("array2DCloseSuite", reporter.lastFailedSuite);
CHECK_EQUAL("filename", reporter.lastFailedFile);
CHECK_EQUAL(line, reporter.lastFailedLine);
}
TEST(CheckArray2DCloseFailureBecauseOfExceptionContainsCorrectDetails)
{
int line = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
UnitTest::TestDetails testDetails("array2DCloseTest", "array2DCloseSuite", "filename", -1);
ScopedCurrentTest scopedResults(testResults, &testDetails);
const float data[2][2] = { {0, 1}, {2, 3} };
CHECK_ARRAY2D_CLOSE (data, ThrowingObject2D(), 2, 2, 0.01f); line = __LINE__;
}
CHECK_EQUAL("array2DCloseTest", reporter.lastFailedTest);
CHECK_EQUAL("array2DCloseSuite", reporter.lastFailedSuite);
CHECK_EQUAL("filename", reporter.lastFailedFile);
CHECK_EQUAL(line, reporter.lastFailedLine);
}
TEST(CheckArray2DCloseFailureIncludesTolerance)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
float const data1[2][2] = { {0, 1}, {2, 3} };
float const data2[2][2] = { {0, 1}, {3, 3} };
CHECK_ARRAY2D_CLOSE (data1, data2, 2, 2, 0.01f);
}
CHECK(strstr(reporter.lastFailedMessage, "0.01"));
}
TEST(CheckArray2DCloseFailsOnException)
{
bool failure = false;
{
RecordingReporter reporter;
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const float data[2][2] = { {0, 1}, {2, 3} };
ThrowingObject2D obj;
CHECK_ARRAY2D_CLOSE (data, obj, 2, 2, 0.01f);
failure = (testResults.GetFailureCount() > 0);
}
CHECK(failure);
}
TEST(CheckArray2DCloseFailureOnExceptionIncludesCheckContents)
{
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
const float data[2][2] = { {0, 1}, {2, 3} };
ThrowingObject2D obj;
CHECK_ARRAY2D_CLOSE (data, obj, 2, 2, 0.01f);
}
CHECK(strstr(reporter.lastFailedMessage, "data"));
CHECK(strstr(reporter.lastFailedMessage, "obj"));
}
float const* const* FunctionWithSideEffects3()
{
++g_sideEffect;
static float const data1[] = {0,1};
static float const data2[] = {2,3};
static const float* const data[] = {data1, data2};
return data;
}
TEST(CheckArray2DCloseDoesNotHaveSideEffectsWhenPassing)
{
g_sideEffect = 0;
{
UnitTest::TestResults testResults;
ScopedCurrentTest scopedResults(testResults);
const float data[2][2] = { {0, 1}, {2, 3} };
CHECK_ARRAY2D_CLOSE (data, FunctionWithSideEffects3(), 2, 2, 0.01f);
}
CHECK_EQUAL(1, g_sideEffect);
}
TEST(CheckArray2DCloseDoesNotHaveSideEffectsWhenFailing)
{
g_sideEffect = 0;
{
UnitTest::TestResults testResults;
ScopedCurrentTest scopedResults(testResults);
const float data[2][2] = { {0, 1}, {3, 3} };
CHECK_ARRAY2D_CLOSE (data, FunctionWithSideEffects3(), 2, 2, 0.01f);
}
CHECK_EQUAL(1, g_sideEffect);
}
}

View File

@ -1,293 +0,0 @@
#include "../UnitTest++.h"
#include "RecordingReporter.h"
using namespace UnitTest;
namespace {
TEST(CheckEqualWithUnsignedLong)
{
TestResults results;
unsigned long something = 2;
CHECK_EQUAL(something, something);
}
TEST(CheckEqualsWithStringsFailsOnDifferentStrings)
{
char txt1[] = "Hello";
char txt2[] = "Hallo";
TestResults results;
CheckEqual(results, txt1, txt2, TestDetails("", "", "", 0));
CHECK_EQUAL(1, results.GetFailureCount());
}
char txt1[] = "Hello"; // non-const on purpose so no folding of duplicate data
char txt2[] = "Hello";
TEST(CheckEqualsWithStringsWorksOnContentsNonConstNonConst)
{
char const* const p1 = txt1;
char const* const p2 = txt2;
TestResults results;
CheckEqual(results, p1, p2, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckEqualsWithStringsWorksOnContentsConstConst)
{
char* const p1 = txt1;
char* const p2 = txt2;
TestResults results;
CheckEqual(results, p1, p2, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckEqualsWithStringsWorksOnContentsNonConstConst)
{
char* const p1 = txt1;
char const* const p2 = txt2;
TestResults results;
CheckEqual(results, p1, p2, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckEqualsWithStringsWorksOnContentsConstNonConst)
{
char const* const p1 = txt1;
char* const p2 = txt2;
TestResults results;
CheckEqual(results, p1, p2, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckEqualsWithStringsWorksOnContentsWithALiteral)
{
char const* const p1 = txt1;
TestResults results;
CheckEqual(results, "Hello", p1, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckEqualFailureIncludesCheckExpectedAndActual)
{
RecordingReporter reporter;
TestResults results(&reporter);
const int something = 2;
CheckEqual(results, 1, something, TestDetails("", "", "", 0));
using namespace std;
CHECK(strstr(reporter.lastFailedMessage, "xpected 1"));
CHECK(strstr(reporter.lastFailedMessage, "was 2"));
}
TEST(CheckEqualFailureIncludesDetails)
{
RecordingReporter reporter;
TestResults results(&reporter);
TestDetails const details("mytest", "mysuite", "file.h", 101);
CheckEqual(results, 1, 2, details);
CHECK_EQUAL("mytest", reporter.lastFailedTest);
CHECK_EQUAL("mysuite", reporter.lastFailedSuite);
CHECK_EQUAL("file.h", reporter.lastFailedFile);
CHECK_EQUAL(101, reporter.lastFailedLine);
}
TEST(CheckCloseTrue)
{
TestResults results;
CheckClose(results, 3.001f, 3.0f, 0.1f, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckCloseFalse)
{
TestResults results;
CheckClose(results, 3.12f, 3.0f, 0.1f, TestDetails("", "", "", 0));
CHECK_EQUAL(1, results.GetFailureCount());
}
TEST(CheckCloseWithZeroEpsilonWorksForSameNumber)
{
TestResults results;
CheckClose(results, 0.1f, 0.1f, 0, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckCloseWithNaNFails)
{
union
{
unsigned int bitpattern;
float nan;
};
bitpattern = 0xFFFFFFFF;
TestResults results;
CheckClose(results, 3.0f, nan, 0.1f, TestDetails("", "", "", 0));
CHECK_EQUAL(1, results.GetFailureCount());
}
TEST(CheckCloseWithNaNAgainstItselfFails)
{
union
{
unsigned int bitpattern;
float nan;
};
bitpattern = 0xFFFFFFFF;
TestResults results;
CheckClose(results, nan, nan, 0.1f, TestDetails("", "", "", 0));
CHECK_EQUAL(1, results.GetFailureCount());
}
TEST(CheckCloseFailureIncludesCheckExpectedAndActual)
{
RecordingReporter reporter;
TestResults results(&reporter);
const float expected = 0.9f;
const float actual = 1.1f;
CheckClose(results, expected, actual, 0.01f, TestDetails("", "", "", 0));
using namespace std;
CHECK(strstr(reporter.lastFailedMessage, "xpected 0.9"));
CHECK(strstr(reporter.lastFailedMessage, "was 1.1"));
}
TEST(CheckCloseFailureIncludesTolerance)
{
RecordingReporter reporter;
TestResults results(&reporter);
CheckClose(results, 2, 3, 0.01f, TestDetails("", "", "", 0));
using namespace std;
CHECK(strstr(reporter.lastFailedMessage, "0.01"));
}
TEST(CheckCloseFailureIncludesDetails)
{
RecordingReporter reporter;
TestResults results(&reporter);
TestDetails const details("mytest", "mysuite", "header.h", 10);
CheckClose(results, 2, 3, 0.01f, details);
CHECK_EQUAL("mytest", reporter.lastFailedTest);
CHECK_EQUAL("mysuite", reporter.lastFailedSuite);
CHECK_EQUAL("header.h", reporter.lastFailedFile);
CHECK_EQUAL(10, reporter.lastFailedLine);
}
TEST(CheckArrayEqualTrue)
{
TestResults results;
int const array[3] = { 1, 2, 3 };
CheckArrayEqual(results, array, array, 3, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckArrayEqualFalse)
{
TestResults results;
int const array1[3] = { 1, 2, 3 };
int const array2[3] = { 1, 2, 2 };
CheckArrayEqual(results, array1, array2, 3, TestDetails("", "", "", 0));
CHECK_EQUAL(1, results.GetFailureCount());
}
TEST(CheckArrayCloseTrue)
{
TestResults results;
float const array1[3] = { 1.0f, 1.5f, 2.0f };
float const array2[3] = { 1.01f, 1.51f, 2.01f };
CheckArrayClose(results, array1, array2, 3, 0.02f, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckArrayCloseFalse)
{
TestResults results;
float const array1[3] = { 1.0f, 1.5f, 2.0f };
float const array2[3] = { 1.01f, 1.51f, 2.01f };
CheckArrayClose(results, array1, array2, 3, 0.001f, TestDetails("", "", "", 0));
CHECK_EQUAL(1, results.GetFailureCount());
}
TEST(CheckArrayCloseFailureIncludesDetails)
{
RecordingReporter reporter;
TestResults results(&reporter);
TestDetails const details("arrayCloseTest", "arrayCloseSuite", "file", 1337);
float const array1[3] = { 1.0f, 1.5f, 2.0f };
float const array2[3] = { 1.01f, 1.51f, 2.01f };
CheckArrayClose(results, array1, array2, 3, 0.001f, details);
CHECK_EQUAL("arrayCloseTest", reporter.lastFailedTest);
CHECK_EQUAL("arrayCloseSuite", reporter.lastFailedSuite);
CHECK_EQUAL("file", reporter.lastFailedFile);
CHECK_EQUAL(1337, reporter.lastFailedLine);
}
TEST(CheckArray2DCloseTrue)
{
TestResults results;
float const array1[3][3] = { { 1.0f, 1.5f, 2.0f },
{ 2.0f, 2.5f, 3.0f },
{ 3.0f, 3.5f, 4.0f } };
float const array2[3][3] = { { 1.01f, 1.51f, 2.01f },
{ 2.01f, 2.51f, 3.01f },
{ 3.01f, 3.51f, 4.01f } };
CheckArray2DClose(results, array1, array2, 3, 3, 0.02f, TestDetails("", "", "", 0));
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(CheckArray2DCloseFalse)
{
TestResults results;
float const array1[3][3] = { { 1.0f, 1.5f, 2.0f },
{ 2.0f, 2.5f, 3.0f },
{ 3.0f, 3.5f, 4.0f } };
float const array2[3][3] = { { 1.01f, 1.51f, 2.01f },
{ 2.01f, 2.51f, 3.01f },
{ 3.01f, 3.51f, 4.01f } };
CheckArray2DClose(results, array1, array2, 3, 3, 0.001f, TestDetails("", "", "", 0));
CHECK_EQUAL(1, results.GetFailureCount());
}
TEST(CheckCloseWithDoublesSucceeds)
{
CHECK_CLOSE(0.5, 0.5, 0.0001);
}
TEST(CheckArray2DCloseFailureIncludesDetails)
{
RecordingReporter reporter;
TestResults results(&reporter);
TestDetails const details("array2DCloseTest", "array2DCloseSuite", "file", 1234);
float const array1[3][3] = { { 1.0f, 1.5f, 2.0f },
{ 2.0f, 2.5f, 3.0f },
{ 3.0f, 3.5f, 4.0f } };
float const array2[3][3] = { { 1.01f, 1.51f, 2.01f },
{ 2.01f, 2.51f, 3.01f },
{ 3.01f, 3.51f, 4.01f } };
CheckArray2DClose(results, array1, array2, 3, 3, 0.001f, details);
CHECK_EQUAL("array2DCloseTest", reporter.lastFailedTest);
CHECK_EQUAL("array2DCloseSuite", reporter.lastFailedSuite);
CHECK_EQUAL("file", reporter.lastFailedFile);
CHECK_EQUAL(1234, reporter.lastFailedLine);
}
}

View File

@ -1,38 +0,0 @@
#include "../UnitTest++.h"
#include "../CurrentTest.h"
#include "ScopedCurrentTest.h"
namespace
{
TEST(CanSetandGetDetails)
{
bool ok = false;
{
ScopedCurrentTest scopedTest;
const UnitTest::TestDetails* details = reinterpret_cast< const UnitTest::TestDetails* >(12345);
UnitTest::CurrentTest::Details() = details;
ok = (UnitTest::CurrentTest::Details() == details);
}
CHECK(ok);
}
TEST(CanSetAndGetResults)
{
bool ok = false;
{
ScopedCurrentTest scopedTest;
UnitTest::TestResults results;
UnitTest::CurrentTest::Results() = &results;
ok = (UnitTest::CurrentTest::Results() == &results);
}
CHECK(ok);
}
}

View File

@ -1,117 +0,0 @@
#include "../UnitTest++.h"
#include "../DeferredTestReporter.h"
#include "../Config.h"
#include <cstring>
namespace UnitTest
{
namespace
{
#ifdef UNITTEST_USE_CUSTOM_STREAMS
MemoryOutStream& operator <<(MemoryOutStream& lhs, const std::string& rhs)
{
lhs << rhs.c_str();
return lhs;
}
#endif
struct MockDeferredTestReporter : public DeferredTestReporter
{
virtual void ReportSummary(int, int, int, float)
{
}
};
struct DeferredTestReporterFixture
{
DeferredTestReporterFixture()
: testName("UniqueTestName")
, testSuite("UniqueTestSuite")
, fileName("filename.h")
, lineNumber(12)
, details(testName.c_str(), testSuite.c_str(), fileName.c_str(), lineNumber)
{
}
MockDeferredTestReporter reporter;
std::string const testName;
std::string const testSuite;
std::string const fileName;
int const lineNumber;
TestDetails const details;
};
TEST_FIXTURE(DeferredTestReporterFixture, ReportTestStartCreatesANewDeferredTest)
{
reporter.ReportTestStart(details);
CHECK_EQUAL(1, (int)reporter.GetResults().size());
}
TEST_FIXTURE(DeferredTestReporterFixture, ReportTestStartCapturesTestNameAndSuite)
{
reporter.ReportTestStart(details);
DeferredTestResult const& result = reporter.GetResults().at(0);
CHECK_EQUAL(testName.c_str(), result.testName);
CHECK_EQUAL(testSuite.c_str(), result.suiteName);
}
TEST_FIXTURE(DeferredTestReporterFixture, ReportTestEndCapturesTestTime)
{
float const elapsed = 123.45f;
reporter.ReportTestStart(details);
reporter.ReportTestFinish(details, elapsed);
DeferredTestResult const& result = reporter.GetResults().at(0);
CHECK_CLOSE(elapsed, result.timeElapsed, 0.0001f);
}
TEST_FIXTURE(DeferredTestReporterFixture, ReportFailureSavesFailureDetails)
{
char const* failure = "failure";
reporter.ReportTestStart(details);
reporter.ReportFailure(details, failure);
DeferredTestResult const& result = reporter.GetResults().at(0);
CHECK(result.failed == true);
CHECK_EQUAL(fileName.c_str(), result.failureFile);
}
TEST_FIXTURE(DeferredTestReporterFixture, ReportFailureSavesFailureDetailsForMultipleFailures)
{
char const* failure1 = "failure 1";
char const* failure2 = "failure 2";
reporter.ReportTestStart(details);
reporter.ReportFailure(details, failure1);
reporter.ReportFailure(details, failure2);
DeferredTestResult const& result = reporter.GetResults().at(0);
CHECK_EQUAL(2, (int)result.failures.size());
CHECK_EQUAL(failure1, result.failures[0].second);
CHECK_EQUAL(failure2, result.failures[1].second);
}
TEST_FIXTURE(DeferredTestReporterFixture, DeferredTestReporterTakesCopyOfFailureMessage)
{
reporter.ReportTestStart(details);
char failureMessage[128];
char const* goodStr = "Real failure message";
char const* badStr = "Bogus failure message";
using namespace std;
strcpy(failureMessage, goodStr);
reporter.ReportFailure(details, failureMessage);
strcpy(failureMessage, badStr);
DeferredTestResult const& result = reporter.GetResults().at(0);
DeferredTestResult::Failure const& failure = result.failures.at(0);
CHECK_EQUAL(goodStr, failure.second);
}
}}

View File

@ -1,151 +0,0 @@
#include "../UnitTest++.h"
#include "../MemoryOutStream.h"
#include <cstring>
using namespace UnitTest;
using namespace std;
namespace {
TEST(DefaultIsEmptyString)
{
MemoryOutStream const stream;
CHECK(stream.GetText() != 0);
CHECK_EQUAL("", stream.GetText());
}
TEST(StreamingTextCopiesCharacters)
{
MemoryOutStream stream;
stream << "Lalala";
CHECK_EQUAL("Lalala", stream.GetText());
}
TEST(StreamingMultipleTimesConcatenatesResult)
{
MemoryOutStream stream;
stream << "Bork" << "Foo" << "Bar";
CHECK_EQUAL("BorkFooBar", stream.GetText());
}
TEST(StreamingIntWritesCorrectCharacters)
{
MemoryOutStream stream;
stream << (int)123;
CHECK_EQUAL("123", stream.GetText());
}
TEST(StreamingUnsignedIntWritesCorrectCharacters)
{
MemoryOutStream stream;
stream << (unsigned int)123;
CHECK_EQUAL("123", stream.GetText());
}
TEST(StreamingLongWritesCorrectCharacters)
{
MemoryOutStream stream;
stream << (long)(-123);
CHECK_EQUAL("-123", stream.GetText());
}
TEST(StreamingUnsignedLongWritesCorrectCharacters)
{
MemoryOutStream stream;
stream << (unsigned long)123;
CHECK_EQUAL("123", stream.GetText());
}
TEST(StreamingFloatWritesCorrectCharacters)
{
MemoryOutStream stream;
stream << 3.1415f;
CHECK(strstr(stream.GetText(), "3.1415"));
}
TEST(StreamingDoubleWritesCorrectCharacters)
{
MemoryOutStream stream;
stream << 3.1415;
CHECK(strstr(stream.GetText(), "3.1415"));
}
TEST(StreamingPointerWritesCorrectCharacters)
{
MemoryOutStream stream;
int* p = (int*)0x1234;
stream << p;
CHECK(strstr(stream.GetText(), "1234"));
}
TEST(StreamingSizeTWritesCorrectCharacters)
{
MemoryOutStream stream;
size_t const s = 53124;
stream << s;
CHECK_EQUAL("53124", stream.GetText());
}
#ifdef UNITTEST_USE_CUSTOM_STREAMS
TEST(StreamInitialCapacityIsCorrect)
{
MemoryOutStream stream(MemoryOutStream::GROW_CHUNK_SIZE);
CHECK_EQUAL((int)MemoryOutStream::GROW_CHUNK_SIZE, stream.GetCapacity());
}
TEST(StreamInitialCapacityIsMultipleOfGrowChunkSize)
{
MemoryOutStream stream(MemoryOutStream::GROW_CHUNK_SIZE + 1);
CHECK_EQUAL((int)MemoryOutStream::GROW_CHUNK_SIZE * 2, stream.GetCapacity());
}
TEST(ExceedingCapacityGrowsBuffer)
{
MemoryOutStream stream(MemoryOutStream::GROW_CHUNK_SIZE);
stream << "012345678901234567890123456789";
char const* const oldBuffer = stream.GetText();
stream << "0123456789";
CHECK(oldBuffer != stream.GetText());
}
TEST(ExceedingCapacityGrowsBufferByGrowChunk)
{
MemoryOutStream stream(MemoryOutStream::GROW_CHUNK_SIZE);
stream << "0123456789012345678901234567890123456789";
CHECK_EQUAL(MemoryOutStream::GROW_CHUNK_SIZE * 2, stream.GetCapacity());
}
TEST(WritingStringLongerThanCapacityFitsInNewBuffer)
{
MemoryOutStream stream(8);
stream << "0123456789ABCDEF";
CHECK_EQUAL("0123456789ABCDEF", stream.GetText());
}
TEST(WritingIntLongerThanCapacityFitsInNewBuffer)
{
MemoryOutStream stream(8);
stream << "aaaa" << 123456;;
CHECK_EQUAL("aaaa123456", stream.GetText());
}
TEST(WritingFloatLongerThanCapacityFitsInNewBuffer)
{
MemoryOutStream stream(8);
stream << "aaaa" << 123456.0f;;
CHECK_EQUAL("aaaa123456.000000f", stream.GetText());
}
TEST(WritingSizeTLongerThanCapacityFitsInNewBuffer)
{
MemoryOutStream stream(8);
stream << "aaaa" << size_t(32145);
CHECK_EQUAL("aaaa32145", stream.GetText());
}
#endif
}

View File

@ -1,129 +0,0 @@
#include "../UnitTest++.h"
#include "../TestReporter.h"
#include "../TimeHelpers.h"
#include "ScopedCurrentTest.h"
using namespace UnitTest;
namespace {
TEST(PassingTestHasNoFailures)
{
class PassingTest : public Test
{
public:
PassingTest() : Test("passing") {}
virtual void RunImpl() const
{
CHECK(true);
}
};
TestResults results;
{
ScopedCurrentTest scopedResults(results);
PassingTest().Run();
}
CHECK_EQUAL(0, results.GetFailureCount());
}
TEST(FailingTestHasFailures)
{
class FailingTest : public Test
{
public:
FailingTest() : Test("failing") {}
virtual void RunImpl() const
{
CHECK(false);
}
};
TestResults results;
{
ScopedCurrentTest scopedResults(results);
FailingTest().Run();
}
CHECK_EQUAL(1, results.GetFailureCount());
}
TEST(ThrowingTestsAreReportedAsFailures)
{
class CrashingTest : public Test
{
public:
CrashingTest() : Test("throwing") {}
virtual void RunImpl() const
{
throw "Blah";
}
};
TestResults results;
{
ScopedCurrentTest scopedResult(results);
CrashingTest().Run();
}
CHECK_EQUAL(1, results.GetFailureCount());
}
#ifndef UNITTEST_MINGW
TEST(CrashingTestsAreReportedAsFailures)
{
class CrashingTest : public Test
{
public:
CrashingTest() : Test("crashing") {}
virtual void RunImpl() const
{
reinterpret_cast< void (*)() >(0)();
}
};
TestResults results;
{
ScopedCurrentTest scopedResult(results);
CrashingTest().Run();
}
CHECK_EQUAL(1, results.GetFailureCount());
}
#endif
TEST(TestWithUnspecifiedSuiteGetsDefaultSuite)
{
Test test("test");
CHECK(test.m_details.suiteName != NULL);
CHECK_EQUAL("DefaultSuite", test.m_details.suiteName);
}
TEST(TestReflectsSpecifiedSuiteName)
{
Test test("test", "testSuite");
CHECK(test.m_details.suiteName != NULL);
CHECK_EQUAL("testSuite", test.m_details.suiteName);
}
void Fail()
{
CHECK(false);
}
TEST(OutOfCoreCHECKMacrosCanFailTests)
{
TestResults results;
{
ScopedCurrentTest scopedResult(results);
Fail();
}
CHECK_EQUAL(1, results.GetFailureCount());
}
}

View File

@ -1,50 +0,0 @@
#include "../UnitTest++.h"
#include "../TestList.h"
using namespace UnitTest;
namespace {
TEST (TestListIsEmptyByDefault)
{
TestList list;
CHECK (list.GetHead() == 0);
}
TEST (AddingTestSetsHeadToTest)
{
Test test("test");
TestList list;
list.Add(&test);
CHECK (list.GetHead() == &test);
CHECK (test.next == 0);
}
TEST (AddingSecondTestAddsItToEndOfList)
{
Test test1("test1");
Test test2("test2");
TestList list;
list.Add(&test1);
list.Add(&test2);
CHECK (list.GetHead() == &test1);
CHECK (test1.next == &test2);
CHECK (test2.next == 0);
}
TEST (ListAdderAddsTestToList)
{
TestList list;
Test test("");
ListAdder adder(list, &test);
CHECK (list.GetHead() == &test);
CHECK (test.next == 0);
}
}

View File

@ -1,212 +0,0 @@
#include "../UnitTest++.h"
#include "../TestMacros.h"
#include "../TestList.h"
#include "../TestResults.h"
#include "../TestReporter.h"
#include "../ReportAssert.h"
#include "RecordingReporter.h"
#include "ScopedCurrentTest.h"
using namespace UnitTest;
namespace {
TestList list1;
TEST_EX(DummyTest, list1)
{
}
TEST (TestsAreAddedToTheListThroughMacro)
{
CHECK(list1.GetHead() != 0);
CHECK(list1.GetHead()->next == 0);
}
struct ThrowingThingie
{
ThrowingThingie() : dummy(false)
{
if (!dummy)
throw "Oops";
}
bool dummy;
};
TestList list2;
TEST_FIXTURE_EX(ThrowingThingie, DummyTestName, list2)
{
}
TEST (ExceptionsInFixtureAreReportedAsHappeningInTheFixture)
{
RecordingReporter reporter;
TestResults result(&reporter);
{
ScopedCurrentTest scopedResults(result);
list2.GetHead()->Run();
}
CHECK(strstr(reporter.lastFailedMessage, "xception"));
CHECK(strstr(reporter.lastFailedMessage, "fixture"));
CHECK(strstr(reporter.lastFailedMessage, "ThrowingThingie"));
}
struct DummyFixture
{
int x;
};
// We're really testing the macros so we just want them to compile and link
SUITE(TestSuite1)
{
TEST(SimilarlyNamedTestsInDifferentSuitesWork)
{
}
TEST_FIXTURE(DummyFixture, SimilarlyNamedFixtureTestsInDifferentSuitesWork)
{
}
}
SUITE(TestSuite2)
{
TEST(SimilarlyNamedTestsInDifferentSuitesWork)
{
}
TEST_FIXTURE(DummyFixture,SimilarlyNamedFixtureTestsInDifferentSuitesWork)
{
}
}
TestList macroTestList1;
TEST_EX(MacroTestHelper1, macroTestList1)
{
}
TEST(TestAddedWithTEST_EXMacroGetsDefaultSuite)
{
CHECK(macroTestList1.GetHead() != NULL);
CHECK_EQUAL ("MacroTestHelper1", macroTestList1.GetHead()->m_details.testName);
CHECK_EQUAL ("DefaultSuite", macroTestList1.GetHead()->m_details.suiteName);
}
TestList macroTestList2;
TEST_FIXTURE_EX(DummyFixture, MacroTestHelper2, macroTestList2)
{
}
TEST(TestAddedWithTEST_FIXTURE_EXMacroGetsDefaultSuite)
{
CHECK(macroTestList2.GetHead() != NULL);
CHECK_EQUAL ("MacroTestHelper2", macroTestList2.GetHead()->m_details.testName);
CHECK_EQUAL ("DefaultSuite", macroTestList2.GetHead()->m_details.suiteName);
}
struct FixtureCtorThrows
{
FixtureCtorThrows() { throw "exception"; }
};
TestList throwingFixtureTestList1;
TEST_FIXTURE_EX(FixtureCtorThrows, FixtureCtorThrowsTestName, throwingFixtureTestList1)
{
}
TEST(FixturesWithThrowingCtorsAreFailures)
{
CHECK(throwingFixtureTestList1.GetHead() != NULL);
RecordingReporter reporter;
TestResults result(&reporter);
{
ScopedCurrentTest scopedResult(result);
throwingFixtureTestList1.GetHead()->Run();
}
int const failureCount = result.GetFailedTestCount();
CHECK_EQUAL(1, failureCount);
CHECK(strstr(reporter.lastFailedMessage, "while constructing fixture"));
}
struct FixtureDtorThrows
{
~FixtureDtorThrows() { throw "exception"; }
};
TestList throwingFixtureTestList2;
TEST_FIXTURE_EX(FixtureDtorThrows, FixtureDtorThrowsTestName, throwingFixtureTestList2)
{
}
TEST(FixturesWithThrowingDtorsAreFailures)
{
CHECK(throwingFixtureTestList2.GetHead() != NULL);
RecordingReporter reporter;
TestResults result(&reporter);
{
ScopedCurrentTest scopedResult(result);
throwingFixtureTestList2.GetHead()->Run();
}
int const failureCount = result.GetFailedTestCount();
CHECK_EQUAL(1, failureCount);
CHECK(strstr(reporter.lastFailedMessage, "while destroying fixture"));
}
const int FailingLine = 123;
struct FixtureCtorAsserts
{
FixtureCtorAsserts()
{
UnitTest::ReportAssert("assert failure", "file", FailingLine);
}
};
TestList ctorAssertFixtureTestList;
TEST_FIXTURE_EX(FixtureCtorAsserts, CorrectlyReportsAssertFailureInCtor, ctorAssertFixtureTestList)
{
}
TEST(CorrectlyReportsFixturesWithCtorsThatAssert)
{
RecordingReporter reporter;
TestResults result(&reporter);
{
ScopedCurrentTest scopedResults(result);
ctorAssertFixtureTestList.GetHead()->Run();
}
const int failureCount = result.GetFailedTestCount();
CHECK_EQUAL(1, failureCount);
CHECK_EQUAL(FailingLine, reporter.lastFailedLine);
CHECK(strstr(reporter.lastFailedMessage, "assert failure"));
}
}
// We're really testing if it's possible to use the same suite in two files
// to compile and link successfuly (TestTestSuite.cpp has suite with the same name)
// Note: we are outside of the anonymous namespace
SUITE(SameTestSuite)
{
TEST(DummyTest1)
{
}
}
#define CUR_TEST_NAME CurrentTestDetailsContainCurrentTestInfo
#define INNER_STRINGIFY(X) #X
#define STRINGIFY(X) INNER_STRINGIFY(X)
TEST(CUR_TEST_NAME)
{
const UnitTest::TestDetails* details = CurrentTest::Details();
CHECK_EQUAL(STRINGIFY(CUR_TEST_NAME), details->testName);
}
#undef CUR_TEST_NAME
#undef INNER_STRINGIFY
#undef STRINGIFY

View File

@ -1,111 +0,0 @@
#include "../UnitTest++.h"
#include "../TestResults.h"
#include "RecordingReporter.h"
using namespace UnitTest;
namespace {
TestDetails const details("testname", "suitename", "filename", 123);
TEST(StartsWithNoTestsRun)
{
TestResults results;
CHECK_EQUAL (0, results.GetTotalTestCount());
}
TEST(RecordsNumbersOfTests)
{
TestResults results;
results.OnTestStart(details);
results.OnTestStart(details);
results.OnTestStart(details);
CHECK_EQUAL(3, results.GetTotalTestCount());
}
TEST(StartsWithNoTestsFailing)
{
TestResults results;
CHECK_EQUAL (0, results.GetFailureCount());
}
TEST(RecordsNumberOfFailures)
{
TestResults results;
results.OnTestFailure(details, "");
results.OnTestFailure(details, "");
CHECK_EQUAL(2, results.GetFailureCount());
}
TEST(RecordsNumberOfFailedTests)
{
TestResults results;
results.OnTestStart(details);
results.OnTestFailure(details, "");
results.OnTestFinish(details, 0);
results.OnTestStart(details);
results.OnTestFailure(details, "");
results.OnTestFailure(details, "");
results.OnTestFailure(details, "");
results.OnTestFinish(details, 0);
CHECK_EQUAL (2, results.GetFailedTestCount());
}
TEST(NotifiesReporterOfTestStartWithCorrectInfo)
{
RecordingReporter reporter;
TestResults results(&reporter);
results.OnTestStart(details);
CHECK_EQUAL (1, reporter.testRunCount);
CHECK_EQUAL ("suitename", reporter.lastStartedSuite);
CHECK_EQUAL ("testname", reporter.lastStartedTest);
}
TEST(NotifiesReporterOfTestFailureWithCorrectInfo)
{
RecordingReporter reporter;
TestResults results(&reporter);
results.OnTestFailure(details, "failurestring");
CHECK_EQUAL (1, reporter.testFailedCount);
CHECK_EQUAL ("filename", reporter.lastFailedFile);
CHECK_EQUAL (123, reporter.lastFailedLine);
CHECK_EQUAL ("suitename", reporter.lastFailedSuite);
CHECK_EQUAL ("testname", reporter.lastFailedTest);
CHECK_EQUAL ("failurestring", reporter.lastFailedMessage);
}
TEST(NotifiesReporterOfCheckFailureWithCorrectInfo)
{
RecordingReporter reporter;
TestResults results(&reporter);
results.OnTestFailure(details, "failurestring");
CHECK_EQUAL (1, reporter.testFailedCount);
CHECK_EQUAL ("filename", reporter.lastFailedFile);
CHECK_EQUAL (123, reporter.lastFailedLine);
CHECK_EQUAL ("testname", reporter.lastFailedTest);
CHECK_EQUAL ("suitename", reporter.lastFailedSuite);
CHECK_EQUAL ("failurestring", reporter.lastFailedMessage);
}
TEST(NotifiesReporterOfTestEnd)
{
RecordingReporter reporter;
TestResults results(&reporter);
results.OnTestFinish(details, 0.1234f);
CHECK_EQUAL (1, reporter.testFinishedCount);
CHECK_EQUAL ("testname", reporter.lastFinishedTest);
CHECK_EQUAL ("suitename", reporter.lastFinishedSuite);
CHECK_CLOSE (0.1234f, reporter.lastFinishedTestTime, 0.0001f);
}
}

View File

@ -1,307 +0,0 @@
#include "../UnitTest++.h"
#include "RecordingReporter.h"
#include "../ReportAssert.h"
#include "../TestList.h"
#include "../TimeHelpers.h"
#include "../TimeConstraint.h"
using namespace UnitTest;
namespace
{
struct MockTest : public Test
{
MockTest(char const* testName, bool const success_, bool const assert_, int const count_ = 1)
: Test(testName)
, success(success_)
, asserted(assert_)
, count(count_)
{
}
virtual void RunImpl(TestResults& testResults_) const
{
for (int i=0; i < count; ++i)
{
if (asserted)
ReportAssert("desc", "file", 0);
else if (!success)
testResults_.OnTestFailure(m_details, "message");
}
}
bool const success;
bool const asserted;
int const count;
};
struct TestRunnerFixture
{
TestRunnerFixture()
: runner(reporter)
{
}
RecordingReporter reporter;
TestList list;
TestRunner runner;
};
TEST_FIXTURE(TestRunnerFixture, TestStartIsReportedCorrectly)
{
MockTest test("goodtest", true, false);
list.Add(&test);
runner.RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
}
TEST_FIXTURE(TestRunnerFixture, TestFinishIsReportedCorrectly)
{
MockTest test("goodtest", true, false);
list.Add(&test);
runner.RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(1, reporter.testFinishedCount);
CHECK_EQUAL("goodtest", reporter.lastFinishedTest);
}
class SlowTest : public Test
{
public:
SlowTest() : Test("slow", "somesuite", "filename", 123) {}
virtual void RunImpl(TestResults&) const
{
TimeHelpers::SleepMs(20);
}
};
TEST_FIXTURE(TestRunnerFixture, TestFinishIsCalledWithCorrectTime)
{
SlowTest test;
list.Add(&test);
runner.RunTestsIf(list, NULL, True(), 0);
CHECK(reporter.lastFinishedTestTime >= 0.005f && reporter.lastFinishedTestTime <= 0.050f);
}
TEST_FIXTURE(TestRunnerFixture, FailureCountIsZeroWhenNoTestsAreRun)
{
CHECK_EQUAL(0, runner.RunTestsIf(list, NULL, True(), 0));
CHECK_EQUAL(0, reporter.testRunCount);
CHECK_EQUAL(0, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, CallsReportFailureOncePerFailingTest)
{
MockTest test1("test", false, false);
list.Add(&test1);
MockTest test2("test", true, false);
list.Add(&test2);
MockTest test3("test", false, false);
list.Add(&test3);
CHECK_EQUAL(2, runner.RunTestsIf(list, NULL, True(), 0));
CHECK_EQUAL(2, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, TestsThatAssertAreReportedAsFailing)
{
MockTest test("test", true, true);
list.Add(&test);
runner.RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(1, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfTestCount)
{
MockTest test1("test", true, false);
MockTest test2("test", true, false);
MockTest test3("test", true, false);
list.Add(&test1);
list.Add(&test2);
list.Add(&test3);
runner.RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(3, reporter.summaryTotalTestCount);
}
TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailedTests)
{
MockTest test1("test", false, false, 2);
MockTest test2("test", true, false);
MockTest test3("test", false, false, 3);
list.Add(&test1);
list.Add(&test2);
list.Add(&test3);
runner.RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(2, reporter.summaryFailedTestCount);
}
TEST_FIXTURE(TestRunnerFixture, ReporterNotifiedOfFailures)
{
MockTest test1("test", false, false, 2);
MockTest test2("test", true, false);
MockTest test3("test", false, false, 3);
list.Add(&test1);
list.Add(&test2);
list.Add(&test3);
runner.RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(5, reporter.summaryFailureCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestPassesForHighTimeThreshold)
{
SlowTest test;
list.Add(&test);
runner.RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(0, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestFailsForLowTimeThreshold)
{
SlowTest test;
list.Add(&test);
runner.RunTestsIf(list, NULL, True(), 3);
CHECK_EQUAL(1, reporter.testFailedCount);
}
TEST_FIXTURE(TestRunnerFixture, SlowTestHasCorrectFailureInformation)
{
SlowTest test;
list.Add(&test);
runner.RunTestsIf(list, NULL, True(), 3);
using namespace std;
CHECK_EQUAL(test.m_details.testName, reporter.lastFailedTest);
CHECK(strstr(test.m_details.filename, reporter.lastFailedFile));
CHECK_EQUAL(test.m_details.lineNumber, reporter.lastFailedLine);
CHECK(strstr(reporter.lastFailedMessage, "Global time constraint failed"));
CHECK(strstr(reporter.lastFailedMessage, "3ms"));
}
TEST_FIXTURE(TestRunnerFixture, SlowTestWithTimeExemptionPasses)
{
class SlowExemptedTest : public Test
{
public:
SlowExemptedTest() : Test("slowexempted", "", 0) {}
virtual void RunImpl(TestResults&) const
{
UNITTEST_TIME_CONSTRAINT_EXEMPT();
TimeHelpers::SleepMs(20);
}
};
SlowExemptedTest test;
list.Add(&test);
runner.RunTestsIf(list, NULL, True(), 3);
CHECK_EQUAL(0, reporter.testFailedCount);
}
struct TestSuiteFixture
{
TestSuiteFixture()
: test1("TestInDefaultSuite")
, test2("TestInOtherSuite", "OtherSuite")
, test3("SecondTestInDefaultSuite")
, runner(reporter)
{
list.Add(&test1);
list.Add(&test2);
}
Test test1;
Test test2;
Test test3;
RecordingReporter reporter;
TestList list;
TestRunner runner;
};
TEST_FIXTURE(TestSuiteFixture, TestRunnerRunsAllSuitesIfNullSuiteIsPassed)
{
runner.RunTestsIf(list, NULL, True(), 0);
CHECK_EQUAL(2, reporter.summaryTotalTestCount);
}
TEST_FIXTURE(TestSuiteFixture,TestRunnerRunsOnlySpecifiedSuite)
{
runner.RunTestsIf(list, "OtherSuite", True(), 0);
CHECK_EQUAL(1, reporter.summaryTotalTestCount);
CHECK_EQUAL("TestInOtherSuite", reporter.lastFinishedTest);
}
struct RunTestIfNameIs
{
RunTestIfNameIs(char const* name_)
: name(name_)
{
}
bool operator()(const Test* const test) const
{
using namespace std;
return (0 == strcmp(test->m_details.testName, name));
}
char const* name;
};
TEST(TestMockPredicateBehavesCorrectly)
{
RunTestIfNameIs predicate("pass");
Test pass("pass");
Test fail("fail");
CHECK(predicate(&pass));
CHECK(!predicate(&fail));
}
TEST_FIXTURE(TestRunnerFixture, TestRunnerRunsTestsThatPassPredicate)
{
Test should_run("goodtest");
list.Add(&should_run);
Test should_not_run("badtest");
list.Add(&should_not_run);
runner.RunTestsIf(list, NULL, RunTestIfNameIs("goodtest"), 0);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
}
TEST_FIXTURE(TestRunnerFixture, TestRunnerOnlyRunsTestsInSpecifiedSuiteAndThatPassPredicate)
{
Test runningTest1("goodtest", "suite");
Test skippedTest2("goodtest");
Test skippedTest3("badtest", "suite");
Test skippedTest4("badtest");
list.Add(&runningTest1);
list.Add(&skippedTest2);
list.Add(&skippedTest3);
list.Add(&skippedTest4);
runner.RunTestsIf(list, "suite", RunTestIfNameIs("goodtest"), 0);
CHECK_EQUAL(1, reporter.testRunCount);
CHECK_EQUAL("goodtest", reporter.lastStartedTest);
CHECK_EQUAL("suite", reporter.lastStartedSuite);
}
}

View File

@ -1,12 +0,0 @@
#include "../UnitTest++.h"
// We're really testing if it's possible to use the same suite in two files
// to compile and link successfuly (TestTestSuite.cpp has suite with the same name)
// Note: we are outside of the anonymous namespace
SUITE(SameTestSuite)
{
TEST(DummyTest2)
{
}
}

View File

@ -1,69 +0,0 @@
#include "../UnitTest++.h"
#include "../TestResults.h"
#include "../TimeHelpers.h"
#include "RecordingReporter.h"
#include "ScopedCurrentTest.h"
using namespace UnitTest;
namespace
{
TEST(TimeConstraintSucceedsWithFastTest)
{
TestResults result;
{
ScopedCurrentTest scopedResult(result);
TimeConstraint t(200, TestDetails("", "", "", 0));
TimeHelpers::SleepMs(5);
}
CHECK_EQUAL(0, result.GetFailureCount());
}
TEST(TimeConstraintFailsWithSlowTest)
{
TestResults result;
{
ScopedCurrentTest scopedResult(result);
TimeConstraint t(10, TestDetails("", "", "", 0));
TimeHelpers::SleepMs(20);
}
CHECK_EQUAL(1, result.GetFailureCount());
}
TEST(TimeConstraintFailureIncludesCorrectData)
{
RecordingReporter reporter;
TestResults result(&reporter);
{
ScopedCurrentTest scopedResult(result);
TestDetails const details("testname", "suitename", "filename", 10);
TimeConstraint t(10, details);
TimeHelpers::SleepMs(20);
}
using namespace std;
CHECK(strstr(reporter.lastFailedFile, "filename"));
CHECK_EQUAL(10, reporter.lastFailedLine);
CHECK(strstr(reporter.lastFailedTest, "testname"));
}
TEST(TimeConstraintFailureIncludesTimeoutInformation)
{
RecordingReporter reporter;
TestResults result(&reporter);
{
ScopedCurrentTest scopedResult(result);
TimeConstraint t(10, TestDetails("", "", "", 0));
TimeHelpers::SleepMs(20);
}
using namespace std;
CHECK(strstr(reporter.lastFailedMessage, "ime constraint"));
CHECK(strstr(reporter.lastFailedMessage, "under 10ms"));
}
}

View File

@ -1,65 +0,0 @@
#include "../UnitTest++.h"
#include "../TimeHelpers.h"
#include "RecordingReporter.h"
#include "ScopedCurrentTest.h"
namespace {
TEST(TimeConstraintMacroQualifiesNamespace)
{
// If this compiles without a "using namespace UnitTest;", all is well.
UNITTEST_TIME_CONSTRAINT(1);
}
TEST(TimeConstraintMacroUsesCorrectInfo)
{
int testLine = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
UNITTEST_TIME_CONSTRAINT(10); testLine = __LINE__;
UnitTest::TimeHelpers::SleepMs(20);
}
using namespace std;
CHECK_EQUAL(1, reporter.testFailedCount);
CHECK(strstr(reporter.lastFailedFile, __FILE__));
CHECK_EQUAL(testLine, reporter.lastFailedLine);
CHECK(strstr(reporter.lastFailedTest, "TimeConstraintMacroUsesCorrectInfo"));
}
TEST(TimeConstraintMacroComparesAgainstPreciseActual)
{
int testLine = 0;
RecordingReporter reporter;
{
UnitTest::TestResults testResults(&reporter);
ScopedCurrentTest scopedResults(testResults);
UNITTEST_TIME_CONSTRAINT(1); testLine = __LINE__;
// start a new timer and run until we're as little over the 1 msec
// threshold as we can achieve; this should guarantee that the "test"
// runs in some very small amount of time > 1 msec
UnitTest::Timer myTimer;
myTimer.Start();
while (myTimer.GetTimeInMs() < 1.001)
UnitTest::TimeHelpers::SleepMs(0);
}
using namespace std;
CHECK_EQUAL(1, reporter.testFailedCount);
CHECK(strstr(reporter.lastFailedFile, __FILE__));
CHECK_EQUAL(testLine, reporter.lastFailedLine);
CHECK(strstr(reporter.lastFailedTest, "TimeConstraintMacroComparesAgainstPreciseActual"));
}
}

View File

@ -1,156 +0,0 @@
#include "../UnitTest++.h"
#include "../ReportAssert.h"
#include "ScopedCurrentTest.h"
#include <vector>
// These are sample tests that show the different features of the framework
namespace {
TEST(ValidCheckSucceeds)
{
bool const b = true;
CHECK(b);
}
TEST(CheckWorksWithPointers)
{
void* p = (void *)0x100;
CHECK(p);
CHECK(p != 0);
}
TEST(ValidCheckEqualSucceeds)
{
int const x = 3;
int const y = 3;
CHECK_EQUAL(x, y);
}
TEST(CheckEqualWorksWithPointers)
{
void* p = (void *)0;
CHECK_EQUAL((void*)0, p);
}
TEST(ValidCheckCloseSucceeds)
{
CHECK_CLOSE(2.0f, 2.001f, 0.01f);
CHECK_CLOSE(2.001f, 2.0f, 0.01f);
}
TEST(ArrayCloseSucceeds)
{
float const a1[] = {1, 2, 3};
float const a2[] = {1, 2.01f, 3};
CHECK_ARRAY_CLOSE(a1, a2, 3, 0.1f);
}
TEST (CheckArrayCloseWorksWithVectors)
{
std::vector< float > a(4);
for (int i = 0; i < 4; ++i)
a[i] = (float)i;
CHECK_ARRAY_CLOSE(a, a, (int)a.size(), 0.0001f);
}
TEST(CheckThrowMacroSucceedsOnCorrectException)
{
struct TestException {};
CHECK_THROW(throw TestException(), TestException);
}
TEST(CheckAssertSucceeds)
{
CHECK_ASSERT(UnitTest::ReportAssert("desc", "file", 0));
}
TEST(CheckThrowMacroFailsOnMissingException)
{
class NoThrowTest : public UnitTest::Test
{
public:
NoThrowTest() : Test("nothrow") {}
void DontThrow() const
{
}
virtual void RunImpl() const
{
CHECK_THROW(DontThrow(), int);
}
};
UnitTest::TestResults results;
{
ScopedCurrentTest scopedResults(results);
NoThrowTest test;
test.Run();
}
CHECK_EQUAL(1, results.GetFailureCount());
}
TEST(CheckThrowMacroFailsOnWrongException)
{
class WrongThrowTest : public UnitTest::Test
{
public:
WrongThrowTest() : Test("wrongthrow") {}
virtual void RunImpl() const
{
CHECK_THROW(throw "oops", int);
}
};
UnitTest::TestResults results;
{
ScopedCurrentTest scopedResults(results);
WrongThrowTest test;
test.Run();
}
CHECK_EQUAL(1, results.GetFailureCount());
}
struct SimpleFixture
{
SimpleFixture()
{
++instanceCount;
}
~SimpleFixture()
{
--instanceCount;
}
static int instanceCount;
};
int SimpleFixture::instanceCount = 0;
TEST_FIXTURE(SimpleFixture, DefaultFixtureCtorIsCalled)
{
CHECK(SimpleFixture::instanceCount > 0);
}
TEST_FIXTURE(SimpleFixture, OnlyOneFixtureAliveAtATime)
{
CHECK_EQUAL(1, SimpleFixture::instanceCount);
}
void CheckBool(const bool b)
{
CHECK(b);
}
TEST(CanCallCHECKOutsideOfTestFunction)
{
CheckBool(true);
}
}

View File

@ -1,183 +0,0 @@
#include "../UnitTest++.h"
#include "../XmlTestReporter.h"
#include <sstream>
using namespace UnitTest;
using std::ostringstream;
namespace
{
#ifdef UNITTEST_USE_CUSTOM_STREAMS
// Overload to let MemoryOutStream accept std::string
MemoryOutStream& operator<<(MemoryOutStream& s, const std::string& value)
{
s << value.c_str();
return s;
}
#endif
struct XmlTestReporterFixture
{
XmlTestReporterFixture()
: reporter(output)
{
}
ostringstream output;
XmlTestReporter reporter;
};
TEST_FIXTURE(XmlTestReporterFixture, MultipleCharactersAreEscaped)
{
TestDetails const details("TestName", "suite", "filename.h", 4321);
reporter.ReportTestStart(details);
reporter.ReportFailure(details, "\"\"\'\'&&<<>>");
reporter.ReportTestFinish(details, 0.1f);
reporter.ReportSummary(1, 2, 3, 0.1f);
char const* expected =
"<?xml version=\"1.0\"?>"
"<unittest-results tests=\"1\" failedtests=\"2\" failures=\"3\" time=\"0.1\">"
"<test suite=\"suite\" name=\"TestName\" time=\"0.1\">"
"<failure message=\"filename.h(4321) : "
"&quot;&quot;&apos;&apos;&amp;&amp;&lt;&lt;&gt;&gt;\"/>"
"</test>"
"</unittest-results>";
CHECK_EQUAL(expected, output.str());
}
TEST_FIXTURE(XmlTestReporterFixture, OutputIsCachedUntilReportSummaryIsCalled)
{
TestDetails const details("", "", "", 0);
reporter.ReportTestStart(details);
reporter.ReportFailure(details, "message");
reporter.ReportTestFinish(details, 1.0F);
CHECK(output.str().empty());
reporter.ReportSummary(1, 1, 1, 1.0f);
CHECK(!output.str().empty());
}
TEST_FIXTURE(XmlTestReporterFixture, EmptyReportSummaryFormat)
{
reporter.ReportSummary(0, 0, 0, 0.1f);
const char *expected =
"<?xml version=\"1.0\"?>"
"<unittest-results tests=\"0\" failedtests=\"0\" failures=\"0\" time=\"0.1\">"
"</unittest-results>";
CHECK_EQUAL(expected, output.str());
}
TEST_FIXTURE(XmlTestReporterFixture, SingleSuccessfulTestReportSummaryFormat)
{
TestDetails const details("TestName", "DefaultSuite", "", 0);
reporter.ReportTestStart(details);
reporter.ReportSummary(1, 0, 0, 0.1f);
const char *expected =
"<?xml version=\"1.0\"?>"
"<unittest-results tests=\"1\" failedtests=\"0\" failures=\"0\" time=\"0.1\">"
"<test suite=\"DefaultSuite\" name=\"TestName\" time=\"0\"/>"
"</unittest-results>";
CHECK_EQUAL(expected, output.str());
}
TEST_FIXTURE(XmlTestReporterFixture, SingleFailedTestReportSummaryFormat)
{
TestDetails const details("A Test", "suite", "A File", 4321);
reporter.ReportTestStart(details);
reporter.ReportFailure(details, "A Failure");
reporter.ReportSummary(1, 1, 1, 0.1f);
const char *expected =
"<?xml version=\"1.0\"?>"
"<unittest-results tests=\"1\" failedtests=\"1\" failures=\"1\" time=\"0.1\">"
"<test suite=\"suite\" name=\"A Test\" time=\"0\">"
"<failure message=\"A File(4321) : A Failure\"/>"
"</test>"
"</unittest-results>";
CHECK_EQUAL(expected, output.str());
}
TEST_FIXTURE(XmlTestReporterFixture, FailureMessageIsXMLEscaped)
{
TestDetails const details("TestName", "suite", "filename.h", 4321);
reporter.ReportTestStart(details);
reporter.ReportFailure(details, "\"\'&<>");
reporter.ReportTestFinish(details, 0.1f);
reporter.ReportSummary(1, 1, 1, 0.1f);
char const* expected =
"<?xml version=\"1.0\"?>"
"<unittest-results tests=\"1\" failedtests=\"1\" failures=\"1\" time=\"0.1\">"
"<test suite=\"suite\" name=\"TestName\" time=\"0.1\">"
"<failure message=\"filename.h(4321) : &quot;&apos;&amp;&lt;&gt;\"/>"
"</test>"
"</unittest-results>";
CHECK_EQUAL(expected, output.str());
}
TEST_FIXTURE(XmlTestReporterFixture, OneFailureAndOneSuccess)
{
TestDetails const failedDetails("FailedTest", "suite", "fail.h", 1);
reporter.ReportTestStart(failedDetails);
reporter.ReportFailure(failedDetails, "expected 1 but was 2");
reporter.ReportTestFinish(failedDetails, 0.1f);
TestDetails const succeededDetails("SucceededTest", "suite", "", 0);
reporter.ReportTestStart(succeededDetails);
reporter.ReportTestFinish(succeededDetails, 1.0f);
reporter.ReportSummary(2, 1, 1, 1.1f);
char const* expected =
"<?xml version=\"1.0\"?>"
"<unittest-results tests=\"2\" failedtests=\"1\" failures=\"1\" time=\"1.1\">"
"<test suite=\"suite\" name=\"FailedTest\" time=\"0.1\">"
"<failure message=\"fail.h(1) : expected 1 but was 2\"/>"
"</test>"
"<test suite=\"suite\" name=\"SucceededTest\" time=\"1\"/>"
"</unittest-results>";
CHECK_EQUAL(expected, output.str());
}
TEST_FIXTURE(XmlTestReporterFixture, MultipleFailures)
{
TestDetails const failedDetails1("FailedTest", "suite", "fail.h", 1);
TestDetails const failedDetails2("FailedTest", "suite", "fail.h", 31);
reporter.ReportTestStart(failedDetails1);
reporter.ReportFailure(failedDetails1, "expected 1 but was 2");
reporter.ReportFailure(failedDetails2, "expected one but was two");
reporter.ReportTestFinish(failedDetails1, 0.1f);
reporter.ReportSummary(1, 1, 2, 1.1f);
char const* expected =
"<?xml version=\"1.0\"?>"
"<unittest-results tests=\"1\" failedtests=\"1\" failures=\"2\" time=\"1.1\">"
"<test suite=\"suite\" name=\"FailedTest\" time=\"0.1\">"
"<failure message=\"fail.h(1) : expected 1 but was 2\"/>"
"<failure message=\"fail.h(31) : expected one but was two\"/>"
"</test>"
"</unittest-results>";
CHECK_EQUAL(expected, output.str());
}
}

10485
3rdparty/bx/3rdparty/catch/catch.hpp vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -174,6 +174,7 @@ docs:
clean:
@echo Cleaning...
-@rm -rf .build
@mkdir .build
###

View File

@ -32,7 +32,6 @@ function copyLib()
end
dofile "bx.lua"
dofile "unittest++.lua"
dofile "bin2c.lua"
project "bx.test"
@ -46,11 +45,7 @@ project "bx.test"
includedirs {
path.join(BX_DIR, "include"),
path.join(BX_THIRD_PARTY_DIR, "UnitTest++/src"),
}
links {
"UnitTest++",
BX_THIRD_PARTY_DIR,
}
files {

View File

@ -100,7 +100,9 @@ function toolchain(_buildDir, _libDir)
location (path.join(_buildDir, "projects", _ACTION))
if _ACTION == "clean" then
os.rmdir(BUILD_DIR)
os.rmdir(_buildDir)
os.mkdir(_buildDir)
os.exit(1)
end
local androidPlatform = "android-14"
@ -288,7 +290,7 @@ function toolchain(_buildDir, _libDir)
elseif "osx" == _OPTIONS["gcc"] then
if os.is("linux") then
local osxToolchain = "x86_64-apple-darwin13-"
local osxToolchain = "x86_64-apple-darwin15-"
premake.gcc.cc = osxToolchain .. "clang"
premake.gcc.cxx = osxToolchain .. "clang++"
premake.gcc.ar = osxToolchain .. "ar"

View File

@ -1,30 +0,0 @@
--
-- Copyright 2010-2016 Branimir Karadzic. All rights reserved.
-- License: https://github.com/bkaradzic/bx#license-bsd-2-clause
--
project "UnitTest++"
kind "StaticLib"
removeflags {
"NoExceptions",
}
files {
"../3rdparty/UnitTest++/src/*.cpp",
"../3rdparty/UnitTest++/src/*.h",
}
configuration { "linux or osx or android-* or *nacl* or ps4 or rpi or riscv" }
files {
"../3rdparty/UnitTest++/src/Posix/**.cpp",
"../3rdparty/UnitTest++/src/Posix/**.h",
}
configuration { "mingw* or vs*" }
files {
"../3rdparty/UnitTest++/src/Win32/**.cpp",
"../3rdparty/UnitTest++/src/Win32/**.h",
}
configuration {}

View File

@ -3,38 +3,15 @@
* License: https://github.com/bkaradzic/bx#license-bsd-2-clause
*/
/*
* Copyright 2012 Matthew Endsley
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted providing that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#define CATCH_CONFIG_RUNNER
#include "test.h"
int runAllTests()
static const char* s_argv[] = { "bx.test" };
int runAllTests(int _argc, const char* _argv[])
{
DBG(BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME);
return UnitTest::RunAllTests();
return Catch::Session().run(_argc, _argv);
}
#if BX_PLATFORM_ANDROID
@ -42,7 +19,7 @@ int runAllTests()
void ANativeActivity_onCreate(ANativeActivity*, void*, size_t)
{
exit(runAllTests() );
exit(runAllTests(BX_COUNTOF(s_argv), s_argv) );
}
#elif BX_PLATFORM_NACL
# include <ppapi/c/pp_errors.h>
@ -56,7 +33,7 @@ PP_EXPORT const void* PPP_GetInterface(const char* /*_name*/)
PP_EXPORT int32_t PPP_InitializeModule(PP_Module /*_module*/, PPB_GetInterface /*_interface*/)
{
DBG("PPAPI version: %d", PPAPI_RELEASE);
runAllTests();
runAllTests(BX_COUNTOF(s_argv), s_argv);
return PP_ERROR_NOINTERFACE;
}
@ -64,8 +41,8 @@ PP_EXPORT void PPP_ShutdownModule()
{
}
#else
int main()
int main(int _argc, const char* _argv[])
{
return runAllTests();
return runAllTests(_argc, _argv);
}
#endif // BX_PLATFORM

View File

@ -7,7 +7,10 @@
#define __TEST_H__
#include <bx/bx.h>
#include <UnitTest++.h>
#include <catch/catch.hpp>
#define TEST(_x) TEST_CASE(#_x, "")
#define CHECK_EQUAL(_x, _y) REQUIRE(_x == _y)
#include "dbg.h"
#if !BX_COMPILER_MSVC

View File

@ -28,7 +28,6 @@
#include <tinystl/allocator.h>
#include <tinystl/unordered_set.h>
#include <UnitTest++.h>
TEST(uoset_copyctor) {

View File

@ -28,7 +28,6 @@
#include <tinystl/allocator.h>
#include <tinystl/unordered_set.h>
#include <UnitTest++.h>
TEST(uoset_pod_compiles) {

Binary file not shown.

Binary file not shown.

Binary file not shown.