try-catch.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. /*
  3. * An API to allow a function, that may fail, to be executed, and recover in a
  4. * controlled manner.
  5. *
  6. * Copyright (C) 2019, Google LLC.
  7. * Author: Brendan Higgins <brendanhiggins@google.com>
  8. */
  9. #ifndef _KUNIT_TRY_CATCH_H
  10. #define _KUNIT_TRY_CATCH_H
  11. #include <linux/types.h>
  12. typedef void (*kunit_try_catch_func_t)(void *);
  13. struct kunit;
  14. /**
  15. * struct kunit_try_catch - provides a generic way to run code which might fail.
  16. * @test: The test case that is currently being executed.
  17. * @try_result: Contains any errno obtained while running test case.
  18. * @try: The function, the test case, to attempt to run.
  19. * @catch: The function called if @try bails out.
  20. * @context: used to pass user data to the try and catch functions.
  21. *
  22. * kunit_try_catch provides a generic, architecture independent way to execute
  23. * an arbitrary function of type kunit_try_catch_func_t which may bail out by
  24. * calling kunit_try_catch_throw(). If kunit_try_catch_throw() is called, @try
  25. * is stopped at the site of invocation and @catch is called.
  26. *
  27. * struct kunit_try_catch provides a generic interface for the functionality
  28. * needed to implement kunit->abort() which in turn is needed for implementing
  29. * assertions. Assertions allow stating a precondition for a test simplifying
  30. * how test cases are written and presented.
  31. *
  32. * Assertions are like expectations, except they abort (call
  33. * kunit_try_catch_throw()) when the specified condition is not met. This is
  34. * useful when you look at a test case as a logical statement about some piece
  35. * of code, where assertions are the premises for the test case, and the
  36. * conclusion is a set of predicates, rather expectations, that must all be
  37. * true. If your premises are violated, it does not makes sense to continue.
  38. */
  39. struct kunit_try_catch {
  40. /* private: internal use only. */
  41. struct kunit *test;
  42. int try_result;
  43. kunit_try_catch_func_t try;
  44. kunit_try_catch_func_t catch;
  45. unsigned long timeout;
  46. void *context;
  47. };
  48. void kunit_try_catch_run(struct kunit_try_catch *try_catch, void *context);
  49. void __noreturn kunit_try_catch_throw(struct kunit_try_catch *try_catch);
  50. static inline int kunit_try_catch_get_result(struct kunit_try_catch *try_catch)
  51. {
  52. return try_catch->try_result;
  53. }
  54. #endif /* _KUNIT_TRY_CATCH_H */