1# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""Tests for integer division by zero."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21from tensorflow.python.framework import constant_op
22from tensorflow.python.framework import dtypes
23from tensorflow.python.framework import errors_impl
24from tensorflow.python.framework import test_util
25from tensorflow.python.platform import test
26
27
28class ZeroDivisionTest(test.TestCase):
29
30  @test_util.run_deprecated_v1
31  def testZeros(self):
32    with test_util.use_gpu():
33      for dtype in dtypes.uint8, dtypes.int16, dtypes.int32, dtypes.int64:
34        zero = constant_op.constant(0, dtype=dtype)
35        one = constant_op.constant(1, dtype=dtype)
36        bads = [one // zero]
37        if dtype in (dtypes.int32, dtypes.int64):
38          bads.append(one % zero)
39        for bad in bads:
40          try:
41            result = self.evaluate(bad)
42          except errors_impl.OpError as e:
43            # Ideally, we'd get a nice exception.  In theory, this should only
44            # happen on CPU, but 32 bit integer GPU division is actually on
45            # CPU due to a placer bug.
46            # TODO(irving): Make stricter once the placer bug is fixed.
47            self.assertIn('Integer division by zero', str(e))
48          else:
49            # On the GPU, integer division by zero produces all bits set.
50            # But apparently on some GPUs "all bits set" for 64 bit division
51            # means 32 bits set, so we allow 0xffffffff as well.  This isn't
52            # very portable, so we may need to expand this list if other GPUs
53            # do different things.
54            #
55            # XLA constant folds integer division by zero to 1.
56            self.assertTrue(test.is_gpu_available())
57            self.assertIn(result, (-1, 1, 0xff, 0xffffffff))
58
59
60if __name__ == '__main__':
61  test.main()
62