◐ Shell
clean mode source ↗

Return arg in case of invalid param in strftime by itsankitkp · Pull Request #4530 · RustPython/RustPython

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return arg in case of invalid param in strftime #4530

Changes from all commits

Commits

File filter

Filter by extension

Conversations

Failed to load comments.

Loading

Jump to

Jump to file

Failed to load files.

Loading

Diff view
Diff view

3 changes: 2 additions & 1 deletion Lib/test/test_time.py

Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ def test_sleep(self):
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',
Expand Down

5 changes: 5 additions & 0 deletions extra_tests/snippets/stdlib_datetime.py

Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ def __init__(self, offset, name):
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")
Expand Down

12 changes: 11 additions & 1 deletion vm/src/stdlib/time.rs

Original file line number Diff line number Diff line change
Expand Up @@ -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())
}

Expand Down