Skip to content

Commit d4c2fd3

Browse files
committed
Handle panic in case of unsupported format in chrono
Chrono panics in case of unsupported formats, this patch handles such cases and returns supplied format as a result.
1 parent 78e815c commit d4c2fd3

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

Lib/test/test_time.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,8 @@ def test_sleep(self):
157157
self.assertRaises(ValueError, time.sleep, -1)
158158
time.sleep(1.2)
159159

160-
@unittest.skip("TODO: RUSTPYTHON, thread 'main' panicked at 'a Display implementation returned an error unexpectedly: Error'")
160+
# TODO: RUSTPYTHON
161+
@unittest.expectedFailure
161162
def test_strftime(self):
162163
tt = time.gmtime(self.t)
163164
for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',

extra_tests/snippets/stdlib_datetime.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,10 @@ def __init__(self, offset, name):
131131
assert_raises(NotImplementedError, ne.utcoffset, dt)
132132
assert_raises(NotImplementedError, ne.dst, dt)
133133

134+
# unsupport format in strptime should returns arg itself
135+
# XXX this fails because it runs in python not rustpython
136+
assert_equal(_time.strftime("%4Y"), "%4Y")
137+
134138
# XXX: bug #1302
135139
# def test_normal(self):
136140
#fo = FixedOffset(3, "Three")

vm/src/stdlib/time.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,18 @@ mod time {
207207

208208
#[pyfunction]
209209
fn strftime(format: PyStrRef, t: OptionalArg<PyStructTime>, vm: &VirtualMachine) -> PyResult {
210+
use std::fmt::Write;
211+
210212
let instant = t.naive_or_local(vm)?;
211-
let formatted_time = instant.format(format.as_str()).to_string();
213+
let mut formatted_time = String::new();
214+
215+
/*
216+
* chrono doesn't support all formats and it
217+
* raises an error if unsupported format is supplied.
218+
* If error happens, we set result as input arg.
219+
*/
220+
write!(&mut formatted_time, "{}", instant.format(format.as_str()))
221+
.unwrap_or_else(|_| formatted_time = format.to_string());
212222
Ok(vm.ctx.new_str(formatted_time).into())
213223
}
214224

0 commit comments

Comments
 (0)