operator_exception_test.cc 2.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "paddle/fluid/framework/operator.h"
#include <exception>
#include <stdexcept>
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/platform/place.h"

namespace paddle {
namespace framework {

class ExceptionThrownOperator : public OperatorBase {
 public:
  using OperatorBase::OperatorBase;

  template <typename T>
  void SetException(T &&obj) {
    exception_ = std::make_exception_ptr(std::forward<T>(obj));
  }

 protected:
  void RunImpl(const Scope &, const platform::Place &) const override {
    if (exception_) {
      std::rethrow_exception(exception_);
    }
  }

 private:
  std::exception_ptr exception_{nullptr};
};

class StubException : public std::exception {
 public:
  const char *what() const noexcept override { return ""; }
};

template <typename T>
bool ExceptionTestMain(T &&obj, bool set_exception) {
  ExceptionThrownOperator op("", {}, {}, {});
  if (set_exception) {
    op.SetException(std::forward<T>(obj));
  }
  Scope scope;
  try {
    op.Run(scope, platform::CPUPlace());
    return false;
  } catch (T &) {
    return true;
  }
}

TEST(test_operator_exception, test_operator_exception) {
  platform::EnforceNotMet enforce_not_met("", __FILE__, __LINE__);
  ASSERT_TRUE(ExceptionTestMain(enforce_not_met, true));
  ASSERT_FALSE(ExceptionTestMain(enforce_not_met, false));

  platform::EOFException eof("", __FILE__, __LINE__);
  ASSERT_TRUE(ExceptionTestMain(eof, true));
  ASSERT_FALSE(ExceptionTestMain(eof, false));

  StubException stub;
  ASSERT_TRUE(ExceptionTestMain(stub, true));
  ASSERT_FALSE(ExceptionTestMain(stub, false));

  ASSERT_TRUE(ExceptionTestMain(1, true));
  ASSERT_FALSE(ExceptionTestMain(1, false));
}

}  // namespace framework
}  // namespace paddle