Skip to content

Commit

Permalink
XCTestUtil: using __builtin_dump_struct as a fallback to print obje…
Browse files Browse the repository at this point in the history
…ct description
  • Loading branch information
gershnik committed Jan 18, 2024
1 parent 47c0ef0 commit 3536bec
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
32 changes: 22 additions & 10 deletions include/objc-helpers/XCTestUtil.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
#import <XCTest/XCTest.h>

#include <sstream>
#include <cxxabi.h>
#include <string>
#include <stdarg.h>

namespace TestUtil {
using std::to_string;
Expand All @@ -40,14 +41,23 @@ namespace TestUtil {
{ str << obj };
};

inline auto demangle(const char * name) -> std::string {

int status = 0;
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name, nullptr, nullptr, &status),
std::free
};
return (status==0) ? res.get() : name ;
auto sprintf(std::string & res, const char * format, ...) -> int {
va_list vl;
va_start(vl, format);
const int size = vsnprintf(0, 0, format, vl);
va_end(vl);
if (size <= 0)
return size;
size_t appendPos = res.size();
size_t appendSize = size_t(size) + 1;
res.resize(appendPos + appendSize);
va_start(vl, format);
const int ret = vsnprintf(&res[appendPos], appendSize, format, vl);
va_end(vl);
if (ret <= 0)
return ret;
res.resize(appendPos + size_t(ret));
return ret;
}

template<class T>
Expand All @@ -64,7 +74,9 @@ namespace TestUtil {
str << val;
return @(str.str().c_str());
} else {
return [NSString stringWithFormat:@"%s object", demangle(typeid(T).name()).c_str()];
std::string res;
__builtin_dump_struct(&val, sprintf, res);
return @(res.c_str());
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion test/XCTestUtilTests.mm
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ void _XCTFailureHandler(XCTestCase * _Nullable test, BOOL expected, const char *
TEST_CASE( "Generic" ) {
failures.clear();
XCTAssertCppEqual(bar{1}, bar{2});
CHECK_FAILURE(__LINE__ - 1, true, "((bar{1}) equal to (bar{2})) failed: (\"(anonymous namespace)::bar object\") is not equal to (\"(anonymous namespace)::bar object\")", "");
CHECK_FAILURE(__LINE__ - 1, true, "((bar{1}) equal to (bar{2})) failed: (\"(anonymous namespace)::bar {\n int i = 1\n}\n\") is not equal to (\"(anonymous namespace)::bar {\n int i = 2\n}\n\")", "");
}

namespace {
Expand Down

0 comments on commit 3536bec

Please sign in to comment.