Commit 73992b54 by Xiaofei Wang Committed by Copybara-Service

Internal change

PiperOrigin-RevId: 453518316
parent 4b5def2c
...@@ -115,8 +115,19 @@ struct type_caster<absl::Duration> { ...@@ -115,8 +115,19 @@ struct type_caster<absl::Duration> {
// Conversion part 1 (Python->C++) // Conversion part 1 (Python->C++)
bool load(handle src, bool convert) { bool load(handle src, bool convert) {
// Ensure that absl::Duration is converted from a Python datetime.timedelta. if (!convert) {
if (!convert || !hasattr(src, "days") || !hasattr(src, "seconds") || return false;
}
if (PyFloat_Check(src.ptr())) {
value = absl::Seconds(src.cast<double>());
return true;
} else if (PyLong_Check(src.ptr())) {
value = absl::Seconds(src.cast<int64_t>());
return true;
} else {
// Ensure that absl::Duration is converted from a Python
// datetime.timedelta.
if (!hasattr(src, "days") || !hasattr(src, "seconds") ||
!hasattr(src, "microseconds")) { !hasattr(src, "microseconds")) {
return false; return false;
} }
...@@ -125,6 +136,8 @@ struct type_caster<absl::Duration> { ...@@ -125,6 +136,8 @@ struct type_caster<absl::Duration> {
absl::Microseconds(GetInt64Attr(src, "microseconds")); absl::Microseconds(GetInt64Attr(src, "microseconds"));
return true; return true;
} }
return false;
}
// Conversion part 2 (C++ -> Python) // Conversion part 2 (C++ -> Python)
static handle cast(const absl::Duration& src, return_value_policy, handle) { static handle cast(const absl::Duration& src, return_value_policy, handle) {
......
...@@ -46,6 +46,19 @@ class AbslTimeTest(parameterized.TestCase): ...@@ -46,6 +46,19 @@ class AbslTimeTest(parameterized.TestCase):
duration = datetime.timedelta(seconds=self.NEGATIVE_SECS) duration = datetime.timedelta(seconds=self.NEGATIVE_SECS)
self.assertTrue(absl_example.check_duration(duration, self.NEGATIVE_SECS)) self.assertTrue(absl_example.check_duration(duration, self.NEGATIVE_SECS))
def test_pass_float_duration(self):
self.assertTrue(
absl_example.check_duration(self.POSITIVE_SECS, self.POSITIVE_SECS))
def test_pass_integer_duration(self):
self.assertTrue(
absl_example.check_duration(self.SECONDS_IN_DAY, self.SECONDS_IN_DAY))
def test_duration_integer_overflow(self):
duration = 2**129
with self.assertRaises(RuntimeError):
absl_example.check_duration(duration, duration)
def test_return_datetime(self): def test_return_datetime(self):
secs = self.TEST_DATETIME.timestamp() secs = self.TEST_DATETIME.timestamp()
local_tz = tz.gettz() local_tz = tz.gettz()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment