Skip to content

Commit 0c5d333

Browse files
authored
Merge pull request RustPython#1891 from RustPython/coolreader18/fix-codec-tests
Fix a few codecs tests
2 parents 3e6f18c + 8a4af38 commit 0c5d333

File tree

4 files changed

+30
-37
lines changed

4 files changed

+30
-37
lines changed

Lib/_codecs.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def encode(v, encoding=None, errors='strict'):
115115
if not isinstance(errors, str):
116116
raise TypeError("Errors must be a string")
117117
codec = lookup(encoding)
118-
res = codec.encode(v, errors)
118+
res = codec[0](v, errors)
119119
if not isinstance(res, tuple) or len(res) != 2:
120120
raise TypeError("encoder must return a tuple (object, integer)")
121121
return res[0]
@@ -137,7 +137,7 @@ def decode(obj, encoding=None, errors='strict'):
137137
if not isinstance(errors, str):
138138
raise TypeError("Errors must be a string")
139139
codec = lookup(encoding)
140-
res = codec.decode(obj, errors)
140+
res = codec[1](obj, errors)
141141
if not isinstance(res, tuple) or len(res) != 2:
142142
raise TypeError("encoder must return a tuple (object, integer)")
143143
return res[0]
@@ -1347,7 +1347,7 @@ def unicode_encode_ucs1(p, size, errors, limit):
13471347
while collend < len(p) and ord(p[collend]) >= limit:
13481348
collend += 1
13491349
x = unicode_call_errorhandler(errors, encoding, reason, p, collstart, collend, False)
1350-
res += str(x[0])
1350+
res += x[0].encode()
13511351
pos = x[1]
13521352

13531353
return res
@@ -1406,8 +1406,8 @@ def PyUnicode_DecodeUnicodeEscape(s, size, errors):
14061406
pos = 0
14071407
while (pos < size):
14081408
## /* Non-escape characters are interpreted as Unicode ordinals */
1409-
if (s[pos] != '\\') :
1410-
p += chr(ord(s[pos]))
1409+
if (chr(s[pos]) != '\\') :
1410+
p += chr(s[pos])
14111411
pos += 1
14121412
continue
14131413
## /* \ - Escapes */
@@ -1416,7 +1416,7 @@ def PyUnicode_DecodeUnicodeEscape(s, size, errors):
14161416
if pos >= len(s):
14171417
errmessage = "\\ at end of string"
14181418
unicode_call_errorhandler(errors, "unicodeescape", errmessage, s, pos-1, size)
1419-
ch = s[pos]
1419+
ch = chr(s[pos])
14201420
pos += 1
14211421
## /* \x escapes */
14221422
if ch == '\\' : p += '\\'
@@ -1469,24 +1469,24 @@ def PyUnicode_DecodeUnicodeEscape(s, size, errors):
14691469
## /* \N{name} */
14701470
elif ch == 'N':
14711471
message = "malformed \\N character escape"
1472-
#pos += 1
1472+
# pos += 1
14731473
look = pos
14741474
try:
14751475
import unicodedata
14761476
except ImportError:
14771477
message = "\\N escapes not supported (can't load unicodedata module)"
14781478
unicode_call_errorhandler(errors, "unicodeescape", message, s, pos-1, size)
1479-
if look < size and s[look] == '{':
1479+
if look < size and chr(s[look]) == '{':
14801480
#/* look for the closing brace */
1481-
while (look < size and s[look] != '}'):
1481+
while (look < size and chr(s[look]) != '}'):
14821482
look += 1
1483-
if (look > pos+1 and look < size and s[look] == '}'):
1483+
if (look > pos+1 and look < size and chr(s[look]) == '}'):
14841484
#/* found a name. look it up in the unicode database */
14851485
message = "unknown Unicode character name"
14861486
st = s[pos+1:look]
14871487
try:
14881488
chr = unicodedata.lookup("%s" % st)
1489-
except KeyError as e:
1489+
except LookupError as e:
14901490
x = unicode_call_errorhandler(errors, "unicodeescape", message, s, pos-1, look+1)
14911491
else:
14921492
x = chr, look + 1

Lib/test/test_unicode.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2123,8 +2123,6 @@ def test_codecs_idna(self):
21232123
# Test whether trailing dot is preserved
21242124
self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
21252125

2126-
# TODO: RUSTPYTHON
2127-
@unittest.expectedFailure
21282126
def test_codecs_errors(self):
21292127
# Error handling (encoding)
21302128
self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii')

vm/src/obj/objfloat.rs

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,14 @@ fn to_float(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<f64> {
651651
}
652652
}
653653
} else {
654-
return Err(vm.new_type_error(format!("can't convert {} to float", obj.class().name)));
654+
let method = vm.get_method_or_type_error(obj.clone(), "__float__", || {
655+
format!(
656+
"float() argument must be a string or a number, not '{}'",
657+
obj.class().name
658+
)
659+
})?;
660+
let result = vm.invoke(&method, vec![])?;
661+
PyFloatRef::try_from_object(vm, result)?.to_f64()
655662
};
656663
Ok(value)
657664
}
@@ -712,21 +719,6 @@ pub fn get_value(obj: &PyObjectRef) -> f64 {
712719
obj.payload::<PyFloat>().unwrap().value
713720
}
714721

715-
fn make_float(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<f64> {
716-
if let Some(float) = obj.payload_if_subclass::<PyFloat>(vm) {
717-
Ok(float.value)
718-
} else {
719-
let method = vm.get_method_or_type_error(obj.clone(), "__float__", || {
720-
format!(
721-
"float() argument must be a string or a number, not '{}'",
722-
obj.class().name
723-
)
724-
})?;
725-
let result = vm.invoke(&method, vec![])?;
726-
Ok(get_value(&result))
727-
}
728-
}
729-
730722
#[derive(Debug, Copy, Clone, PartialEq)]
731723
pub struct IntoPyFloat {
732724
value: f64,
@@ -741,7 +733,7 @@ impl IntoPyFloat {
741733
impl TryFromObject for IntoPyFloat {
742734
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
743735
Ok(IntoPyFloat {
744-
value: make_float(vm, &obj)?,
736+
value: to_float(vm, &obj)?,
745737
})
746738
}
747739
}

vm/src/obj/objstr.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1173,13 +1173,8 @@ impl PyString {
11731173
}
11741174

11751175
#[pymethod]
1176-
fn encode(
1177-
zelf: PyRef<Self>,
1178-
encoding: OptionalArg<PyStringRef>,
1179-
errors: OptionalArg<PyStringRef>,
1180-
vm: &VirtualMachine,
1181-
) -> PyResult<PyBytesRef> {
1182-
encode_string(zelf, encoding.into_option(), errors.into_option(), vm)
1176+
fn encode(zelf: PyRef<Self>, args: EncodeArgs, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
1177+
encode_string(zelf, args.encoding, args.errors, vm)
11831178
}
11841179

11851180
#[pymethod(magic)]
@@ -1201,6 +1196,14 @@ impl PyString {
12011196
}
12021197
}
12031198

1199+
#[derive(FromArgs)]
1200+
struct EncodeArgs {
1201+
#[pyarg(positional_or_keyword, default = "None")]
1202+
encoding: Option<PyStringRef>,
1203+
#[pyarg(positional_or_keyword, default = "None")]
1204+
errors: Option<PyStringRef>,
1205+
}
1206+
12041207
pub(crate) fn encode_string(
12051208
s: PyStringRef,
12061209
encoding: Option<PyStringRef>,

0 commit comments

Comments
 (0)