Merge pull request #4530 from itsankitkp/handle-panic-strftime-new

Return arg in case of invalid param in strftime
This commit is contained in:
Jeong YunWon
2023-02-22 00:03:04 +09:00
committed by GitHub
3 changed files with 18 additions and 2 deletions

View File

@@ -157,7 +157,8 @@ class TimeTestCase(unittest.TestCase):
self.assertRaises(ValueError, time.sleep, -1)
time.sleep(1.2)
@unittest.skip("TODO: RUSTPYTHON, thread 'main' panicked at 'a Display implementation returned an error unexpectedly: Error'")
# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_strftime(self):
tt = time.gmtime(self.t)
for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',

View File

@@ -131,6 +131,11 @@ assert_raises(NotImplementedError, ne.tzname, dt)
assert_raises(NotImplementedError, ne.utcoffset, dt)
assert_raises(NotImplementedError, ne.dst, dt)
# unsupport format in strptime returns arg itself
# in linux. Todo: add cases for Mac/Windows
if sys.platform.startswith("linux"):
assert_equal(_time.strftime("%?"), "%?")
# XXX: bug #1302
# def test_normal(self):
#fo = FixedOffset(3, "Three")

View File

@@ -207,8 +207,18 @@ mod time {
#[pyfunction]
fn strftime(format: PyStrRef, t: OptionalArg<PyStructTime>, vm: &VirtualMachine) -> PyResult {
use std::fmt::Write;
let instant = t.naive_or_local(vm)?;
let formatted_time = instant.format(format.as_str()).to_string();
let mut formatted_time = String::new();
/*
* chrono doesn't support all formats and it
* raises an error if unsupported format is supplied.
* If error happens, we set result as input arg.
*/
write!(&mut formatted_time, "{}", instant.format(format.as_str()))
.unwrap_or_else(|_| formatted_time = format.to_string());
Ok(vm.ctx.new_str(formatted_time).into())
}