Skip to content

Commit 31d7038

Browse files
committed
Validate input of Time ctor (#90)
1 parent 92b97d6 commit 31d7038

3 files changed

Lines changed: 43 additions & 8 deletions

File tree

CHANGELOG.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ Unreleased
1818

1919
**Fixed**
2020

21+
* Ensure input of ``Time`` is always two integers.
22+
2123
**Deprecated**
2224

2325
**Removed**

src/roslibpy/core.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import json
44
import logging
5+
from multiprocessing.sharedctypes import Value
56
import time
67

78
# Python 2/3 compatibility import list
@@ -12,12 +13,16 @@
1213

1314
LOGGER = logging.getLogger('roslibpy')
1415

15-
__all__ = ['Message',
16-
'ServiceRequest',
17-
'ServiceResponse',
18-
'Topic',
19-
'Service',
20-
'Param']
16+
__all__ = [
17+
'Header',
18+
'Message',
19+
'Param',
20+
'Service',
21+
'ServiceRequest',
22+
'ServiceResponse',
23+
'Time',
24+
'Topic'
25+
]
2126

2227

2328
class Message(UserDict):
@@ -44,8 +49,15 @@ class Time(UserDict):
4449
"""Represents ROS time with two integers: seconds since epoch and nanoseconds since seconds."""
4550
def __init__(self, secs, nsecs):
4651
self.data = {}
47-
self.data['secs'] = secs
48-
self.data['nsecs'] = nsecs
52+
self.data['secs'] = self._ensure_int(secs)
53+
self.data['nsecs'] = self._ensure_int(nsecs)
54+
55+
def _ensure_int(self, n):
56+
if isinstance(n, int):
57+
return n
58+
if isinstance(n, float) and n.is_integer():
59+
return int(n)
60+
raise ValueError('argument must be an integer')
4961

5062
@property
5163
def secs(self):

tests/test_core.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import pytest
2+
13
from roslibpy import Header
24
from roslibpy import Time
35

@@ -37,3 +39,22 @@ def test_header_ctor_supports_dict():
3739
assert header['stamp']['secs'] == 1610122759
3840
assert header['stamp']['secs'] == header['stamp'].secs
3941
assert header['stamp'].to_sec() == REF_FLOAT_SECS_TIME
42+
43+
44+
def test_time_accepts_only_ints():
45+
with pytest.raises(ValueError):
46+
Time(1.3, 1.0)
47+
with pytest.raises(ValueError):
48+
Time(100.0, 3.1)
49+
50+
t = Time(110.0, 0.0)
51+
assert t.secs == 110
52+
assert t.nsecs == 0
53+
54+
55+
def test_time_properties_are_readonly():
56+
t = Time.now()
57+
with pytest.raises(AttributeError):
58+
t.secs = 10
59+
with pytest.raises(AttributeError):
60+
t.nsecs = 10

0 commit comments

Comments
 (0)