|
| 1 | +#include <gmock/gmock.h> |
| 2 | +#include <gtest/gtest.h> |
| 3 | + |
| 4 | +#include "torch_xla/csrc/runtime/debug_macros.h" |
| 5 | +#include "torch_xla/csrc/runtime/env_vars.h" |
| 6 | + |
| 7 | +namespace torch_xla { |
| 8 | +namespace { |
| 9 | + |
| 10 | +using absl::StrCat; |
| 11 | + |
| 12 | +TEST(DebugMacrosTest, Check) { |
| 13 | + auto line = __LINE__ + 1; |
| 14 | + EXPECT_THAT([] { XLA_CHECK(false) << "Error message."; }, |
| 15 | + testing::ThrowsMessage<std::runtime_error>(testing::StartsWith( |
| 16 | + StrCat("Check failed: false: Error message. (at ", __FILE__, |
| 17 | + ":", line, ")\n*** Begin stack trace ***")))); |
| 18 | +} |
| 19 | + |
| 20 | +#define TEST_XLA_CHECK_OP_(opstr, lhs, rhs, compstr, valstr) \ |
| 21 | + TEST(DebugMacrosTest, Check##opstr) { \ |
| 22 | + EXPECT_THAT( \ |
| 23 | + [] { XLA_CHECK_##opstr(lhs, rhs) << " Error message."; }, \ |
| 24 | + testing::ThrowsMessage<std::runtime_error>(testing::StartsWith(StrCat( \ |
| 25 | + "Check failed: " compstr " (" valstr ") Error message. (at ", \ |
| 26 | + __FILE__, ":", __LINE__, ")\n*** Begin stack trace ***")))); \ |
| 27 | + } |
| 28 | + |
| 29 | +#define TEST_XLA_CHECK_OP(opstr, op, lhs, rhs) \ |
| 30 | + TEST_XLA_CHECK_OP_(opstr, lhs, rhs, #lhs " " #op " " #rhs, #lhs " vs. " #rhs) |
| 31 | + |
| 32 | +TEST_XLA_CHECK_OP(EQ, ==, 5, 8) |
| 33 | +TEST_XLA_CHECK_OP(NE, !=, 5, 5) |
| 34 | +TEST_XLA_CHECK_OP(LE, <=, 5, 1) |
| 35 | +TEST_XLA_CHECK_OP(LT, <, 5, 1) |
| 36 | + |
| 37 | +// Since the implementation of GE and GT checks use their corresponding |
| 38 | +// less-than LE and LT versions with their arguments swapped, we need to modify |
| 39 | +// the expected error message accordingly. |
| 40 | +// |
| 41 | +// In other words: |
| 42 | +// |
| 43 | +// XLA_CHECK_GE(5, 8) |
| 44 | +// |
| 45 | +// Errors with the following message: |
| 46 | +// |
| 47 | +// Check failed: 8 <= 5 (8 vs. 5) |
| 48 | +#define TEST_XLA_CHECK_GREATER(opstr, lessop, lhs, rhs) \ |
| 49 | + TEST_XLA_CHECK_OP_(opstr, lhs, rhs, #rhs " " #lessop " " #lhs, \ |
| 50 | + #rhs " vs. " #lhs) |
| 51 | + |
| 52 | +TEST_XLA_CHECK_GREATER(GE, <=, 5, 8) |
| 53 | +TEST_XLA_CHECK_GREATER(GT, <, 5, 8) |
| 54 | + |
| 55 | +} // namespace |
| 56 | +} // namespace torch_xla |
| 57 | + |
| 58 | +static void SetUp() { |
| 59 | + setenv(torch_xla::runtime::env::kEnvShowCppErrorContext, /* value= */ "true", |
| 60 | + /* replace= */ 1); |
| 61 | +} |
| 62 | + |
| 63 | +int main(int argc, char** argv) { |
| 64 | + SetUp(); |
| 65 | + ::testing::InitGoogleTest(&argc, argv); |
| 66 | + return RUN_ALL_TESTS(); |
| 67 | +} |
0 commit comments