From bffb5aaff79397c80020f16b2c9acb6528170389 Mon Sep 17 00:00:00 2001 From: wawltor Date: Fri, 11 Oct 2019 11:16:35 +0800 Subject: [PATCH] Fix the api input type and data dtype check, cherry-pick from develop(#20138) (#20429) Fix the api input type and data dtype check in the op of sign test=release/1.6 --- python/paddle/fluid/layers/nn.py | 12 +++++++++++- .../paddle/fluid/tests/unittests/test_sign_op.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/python/paddle/fluid/layers/nn.py b/python/paddle/fluid/layers/nn.py index 35ce7ff4d58..20ce7f53c90 100755 --- a/python/paddle/fluid/layers/nn.py +++ b/python/paddle/fluid/layers/nn.py @@ -15400,7 +15400,17 @@ def sign(x): helper = LayerHelper("sign", **locals()) if not isinstance(x, Variable): - x = assign(x) + if isinstance(x, np.ndarray): + x = assign(x) + else: + raise TypeError( + "The type of 'x' in sign_op must be Variable or numpy.ndarray, but received %s." + % (type(x))) + + if convert_dtype(x.dtype) not in ['float32', 'float64']: + raise TypeError( + "The data type of 'x' in sign_op must be float32 or float64, but received %s." + % (convert_dtype(x.dtype))) out = helper.create_variable_for_type_inference(dtype=x.dtype) diff --git a/python/paddle/fluid/tests/unittests/test_sign_op.py b/python/paddle/fluid/tests/unittests/test_sign_op.py index 85a9d9cae47..00ac43b9ba5 100644 --- a/python/paddle/fluid/tests/unittests/test_sign_op.py +++ b/python/paddle/fluid/tests/unittests/test_sign_op.py @@ -17,6 +17,8 @@ from __future__ import print_function import unittest import numpy as np from op_test import OpTest +import paddle.fluid as fluid +from paddle.fluid import Program, program_guard class TestSignOp(OpTest): @@ -34,5 +36,17 @@ class TestSignOp(OpTest): self.check_grad(['X'], 'Out') +class TestSignOpError(OpTest): + def test_errors(self): + with program_guard(Program(), Program()): + # The input type of sign_op must be Variable or numpy.ndarray. + input1 = 12 + self.assertRaises(TypeError, fluid.layers.sign, input1) + # The input dtype of sign_op must be float32, float64. + input2 = fluid.layers.data( + name='input2', shape=[12, 10], dtype="int32") + self.assertRaises(TypeError, fluid.layers.sign, input2) + + if __name__ == "__main__": unittest.main() -- GitLab