https://mooseframework.inl.gov
MooseUnitUtils.h
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://mooseframework.inl.gov
3 //*
4 //* All rights reserved, see COPYRIGHT for full restrictions
5 //* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6 //*
7 //* Licensed under LGPL 2.1, please see LICENSE for details
8 //* https://www.gnu.org/licenses/lgpl-2.1.html
9 
10 #pragma once
11 
12 #include "gtest/gtest.h"
13 
14 #include "MooseUtils.h"
15 #include "Moose.h"
16 
18 {
26 template <class ExceptionType = std::exception, class Action = bool>
27 void
28 assertThrows(const Action & action,
29  const std::optional<std::string> & contains = {},
30  const bool set_throw_on_error = false)
31 {
32  static_assert(std::is_base_of_v<std::exception, ExceptionType>, "Not an exception");
33 
34  std::unique_ptr<Moose::ScopedThrowOnError> scoped_throw_on_error;
35  if (set_throw_on_error)
36  scoped_throw_on_error = std::make_unique<Moose::ScopedThrowOnError>();
37 
38  try
39  {
40  action();
41  FAIL() << "Expected " << MooseUtils::prettyCppType<ExceptionType>() << " not thrown";
42  }
43  catch (std::exception const & e)
44  {
45  if constexpr (!std::is_same_v<std::exception, ExceptionType>)
46  if (!dynamic_cast<const ExceptionType *>(&e))
47  FAIL() << "Threw " << demangle(typeid(e).name()) << " instead of "
48  << MooseUtils::prettyCppType<ExceptionType>() << " with message '" << e.what()
49  << "'";
50 
51  if (contains)
52  {
53  ASSERT_TRUE(std::string(e.what()).find(*contains) != std::string::npos)
54  << "Exception \"" << e.what() << "\" does not contain \"" << *contains << "\"";
55  }
56  }
57 }
58 }
std::string name(const ElemQuality q)
KOKKOS_INLINE_FUNCTION const T * find(const T &target, const T *const begin, const T *const end)
Find a value in an array.
Definition: KokkosUtils.h:30
Base class for actions.
Definition: Action.h:33
void assertThrows(const Action &action, const std::optional< std::string > &contains={}, const bool set_throw_on_error=false)
A helper for asserting that calling something throws an exception.
bool contains(std::string_view superstring, std::string_view substring)
std::string demangle(const char *name)