diff --git a/rosidl_generator_py/CMakeLists.txt b/rosidl_generator_py/CMakeLists.txt index 07d124a1..cdae8ee8 100644 --- a/rosidl_generator_py/CMakeLists.txt +++ b/rosidl_generator_py/CMakeLists.txt @@ -53,6 +53,7 @@ if(BUILD_TESTING) msg/BuiltinTypeSequencesIdl.idl msg/StringArrays.msg msg/Property.msg + msg/Float.msg ADD_LINTER_TESTS SKIP_INSTALL ) @@ -79,6 +80,12 @@ if(BUILD_TESTING) APPEND_LIBRARY_DIRS "${_append_library_dirs}" WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/rosidl_generator_py" ) + + ament_add_pytest_test(test_int_to_float_py test/test_int_to_float.py + APPEND_ENV "PYTHONPATH=${pythonpath}" + APPEND_LIBRARY_DIRS "${_append_library_dirs}" + WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/rosidl_generator_py" + ) endif() endif() diff --git a/rosidl_generator_py/msg/Float.msg b/rosidl_generator_py/msg/Float.msg new file mode 100644 index 00000000..91bec70e --- /dev/null +++ b/rosidl_generator_py/msg/Float.msg @@ -0,0 +1 @@ +float32 float_value diff --git a/rosidl_generator_py/resource/_msg.py.em b/rosidl_generator_py/resource/_msg.py.em index 8c21e552..9c862a18 100644 --- a/rosidl_generator_py/resource/_msg.py.em +++ b/rosidl_generator_py/resource/_msg.py.em @@ -481,6 +481,10 @@ if member.name in dict(inspect.getmembers(builtins)).keys(): from collections.abc import ByteString @[ elif isinstance(type_, BasicType) and type_.typename in CHARACTER_TYPES]@ from collections import UserString +@[ end if]@ +@[ if isinstance(type_, BasicType) and type_.typename in FLOATING_POINT_TYPES]@ + if isinstance(value, int): + value = float(value) @[ end if]@ assert \ @[ if isinstance(member.type, AbstractNestedType)]@ diff --git a/rosidl_generator_py/test/test_int_to_float.py b/rosidl_generator_py/test/test_int_to_float.py new file mode 100644 index 00000000..01da3b64 --- /dev/null +++ b/rosidl_generator_py/test/test_int_to_float.py @@ -0,0 +1,26 @@ +# Copyright 2021 Open Source Robotics Foundation, Inc. +# +# 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. + +from rosidl_generator_py.msg import Float + + +def test_int_to_float(): + msg1 = Float(check_types=True, float_value=float(1)) + + assert isinstance(msg1.float_value, float) + assert 1 == msg1.float_value + + msg2 = Float(check_types=True, float_value=int(1)) + assert isinstance(msg2.float_value, float) + assert 1 == msg2.float_value