Skip to content

Commit 61e559c

Browse files
committed
[GR-20539] Make unit tests pass with Python 3.7
PullRequest: graalpython/778
2 parents 3daa036 + 8c6e57b commit 61e559c

26 files changed

+125
-116
lines changed

graalpython/com.oracle.graal.python.test/src/graalpytest.py

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
1+
# Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
22
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
33
#
44
# The Universal Permissive License (UPL), Version 1.0
@@ -233,27 +233,36 @@ def assertIsInstance(self, obj, cls, msg=None):
233233
def fail(self, msg):
234234
assert False, msg
235235

236-
class assertRaises():
237-
def __init__(self, exc_type, function=None, *args, **kwargs):
238-
self.function = function
239-
if self.function is None:
236+
def assertRaises(self, exc_type, function=None, *args, **kwargs):
237+
return self.assertRaisesRegex(exc_type, None, function, *args, **kwargs)
238+
239+
class assertRaisesRegex():
240+
def __init__(self, exc_type, exc_regex, function=None, *args, **kwargs):
241+
import re
242+
function = function
243+
if function is None:
240244
self.exc_type = exc_type
245+
self.exc_regex = exc_regex
241246
else:
242247
try:
243-
self.function(*args, **kwargs)
244-
except exc_type:
245-
pass
248+
function(*args, **kwargs)
249+
except exc_type as exc:
250+
if exc_regex:
251+
assert re.search(exc_regex, str(exc)), "%s does not match %s" % (exc_regex, exc)
246252
else:
247-
assert False, "expected '%r' to raise '%r'" % (self.function, exc_type)
253+
assert False, "expected '%r' to raise '%r'" % (function, exc_type)
248254

249255
def __enter__(self):
250256
return self
251257

252258
def __exit__(self, exc_type, exc, traceback):
259+
import re
253260
if not exc_type:
254-
assert False, "expected '%r' to raise '%r'" % (self.function, self.exc_type)
261+
assert False, "expected '%r' to be raised" % self.exc_type
255262
elif self.exc_type in exc_type.mro():
256263
self.exception = exc
264+
if self.exc_regex:
265+
assert re.search(self.exc_regex, str(exc)), "%s does not match %s" % (self.exc_regex, exc)
257266
return True
258267

259268
def assertIn(self, expected, in_str, msg=""):

graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_codeobject.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
1+
# Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
22
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
33
#
44
# The Universal Permissive License (UPL), Version 1.0
@@ -69,7 +69,7 @@ def compile_module(self, name):
6969
1, 2,
7070
3, 4, 0,
7171
b"", tuple(), tuple(),
72-
tuple(), tuple(), tuple(),
72+
("a", "b", "c"), tuple(), tuple(),
7373
"filename", "name", 1,
7474
b"",
7575
),

graalpython/com.oracle.graal.python.test/src/tests/test_bytes.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
1+
# Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
22
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
33
#
44
# The Universal Permissive License (UPL), Version 1.0
@@ -311,6 +311,7 @@ def test_delitem():
311311
assert b == bytearray()
312312

313313

314+
@unittest.skipIf(sys.version_info.minor < 7, "Requires Python 3.7+")
314315
def test_subclass():
315316

316317
class MyByteArray(bytearray):
@@ -321,7 +322,7 @@ def __str__(self):
321322
b1 = bytearray(range(10))
322323
b2 = MyByteArray(range(10))
323324
assert b1 == b2
324-
assert "<<%s>>" % str(b1) == str(b2)
325+
assert "<<%s>>" % str(b1).replace('bytearray', 'MyByteArray') == str(b2)
325326

326327
class MyBytes(bytes):
327328

graalpython/com.oracle.graal.python.test/src/tests/test_generators.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2018, 2019, Oracle and/or its affiliates.
1+
# Copyright (c) 2018, 2020, Oracle and/or its affiliates.
22
# Copyright (C) 1996-2017 Python Software Foundation
33
#
44
# Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
@@ -207,18 +207,19 @@ def gen():
207207
next(g)
208208
next(g)
209209
self.assertEqual(next(g), "done")
210-
211210

212-
def test_stopiteration_warning(self):
211+
@unittest.skipIf(sys.version_info.minor < 7, "Requires Python 3.7+")
212+
def test_stopiteration_error(self):
213213
# See also PEP 479.
214214

215215
def gen():
216216
raise StopIteration
217217
yield
218218

219-
with self.assertRaises(StopIteration):
219+
with self.assertRaisesRegex(RuntimeError, 'raised StopIteration'):
220220
next(gen())
221221

222+
@unittest.skipIf(sys.version_info.minor < 7, "Requires Python 3.7+")
222223
def test_tutorial_stopiteration(self):
223224
# Raise StopIteration" stops the generator too:
224225

@@ -230,13 +231,9 @@ def f():
230231
g = f()
231232
self.assertEqual(next(g), 1)
232233

233-
with self.assertRaises(StopIteration):
234+
with self.assertRaisesRegex(RuntimeError, 'raised StopIteration'):
234235
next(g)
235236

236-
with self.assertRaises(StopIteration):
237-
# This time StopIteration isn't raised from the generator's body,
238-
# hence no warning.
239-
next(g)
240237

241238
# def test_return_tuple(self):
242239
# def g():

graalpython/com.oracle.graal.python.test/src/tests/test_math.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2018, Oracle and/or its affiliates.
1+
# Copyright (c) 2018, 2020, Oracle and/or its affiliates.
22
# Copyright (C) 1996-2017 Python Software Foundation
33
#
44
# Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
@@ -1332,7 +1332,7 @@ def executeFnTest(self, values, fn, fnName):
13321332
else :
13331333
if result != expected:
13341334
if (sys.version_info.major >= 3 and sys.version_info.minor >= 5):
1335-
self.assertTrue(math.isclose(result, expected, rel_tol=1e-14), "Test3 fail: {}({}) = {}, but was {}".format(fnName, value[0], expected, result))
1335+
self.assertTrue(math.isclose(result, expected, rel_tol=1e-13), "Test3 fail: {}({}) = {}, but was {}".format(fnName, value[0], expected, result))
13361336

13371337
def test_erf(self):
13381338
erfValues = [(0.0, 0.0), (-0.0, -0.0), (INF, 1.0), (NINF, -1.0), (NAN, NAN),

graalpython/com.oracle.graal.python.test/src/tests/test_tuple.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2018, 2019, Oracle and/or its affiliates.
1+
# Copyright (c) 2018, 2020, Oracle and/or its affiliates.
22
# Copyright (C) 1996-2017 Python Software Foundation
33
#
44
# Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
@@ -236,12 +236,10 @@ def __iter__(self):
236236
t = (2,)
237237
tt = tuple((2,))
238238
self.assertEqual(t,tt)
239-
self.assertFalse(t is tt)
240239

241240
ttt = tuple(t)
242241
self.assertEqual(t,ttt)
243242
self.assertEqual(tt,ttt)
244-
self.assertFalse(ttt is tt)
245243
self.assertTrue(ttt is t)
246244

247245
m = MyTuple((2,))

graalpython/com.oracle.graal.python.test/src/tests/test_yield_from.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2018, Oracle and/or its affiliates.
1+
# Copyright (c) 2018, 2020, Oracle and/or its affiliates.
22
# Copyright (C) 1996-2017 Python Software Foundation
33
#
44
# Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
@@ -372,7 +372,7 @@ def g2():
372372
return [42]
373373
self.assertEqual(list(g1()), ["g2"])
374374

375-
375+
@unittest.skipIf(sys.version_info.minor < 7, "Requires Python 3.7+")
376376
def test_generator_return_value(self):
377377
"""
378378
Test generator return value
@@ -419,7 +419,7 @@ def g2(v = None):
419419
"Yielded g2 spam",
420420
"Yielded g2 more spam",
421421
"Finishing g2",
422-
"g2 returned StopIteration(3,)",
422+
"g2 returned StopIteration(3)",
423423
"Yielded g1 eggs",
424424
"Finishing g1",
425425
])
@@ -666,6 +666,7 @@ class LunchError(Exception):
666666
"Finishing g1",
667667
])
668668

669+
@unittest.skipIf(sys.version_info.minor < 7, "Requires Python 3.7+")
669670
def test_next_and_return_with_value(self):
670671
"""
671672
Test next and return with value
@@ -697,17 +698,18 @@ def g(r):
697698
"g starting",
698699
"f resuming g",
699700
"g returning 1",
700-
"f caught StopIteration(1,)",
701+
"f caught StopIteration(1)",
701702
"g starting",
702703
"f resuming g",
703704
"g returning (2,)",
704-
"f caught StopIteration((2,),)",
705+
"f caught StopIteration((2,))",
705706
"g starting",
706707
"f resuming g",
707-
"g returning StopIteration(3,)",
708-
"f caught StopIteration(StopIteration(3,),)",
708+
"g returning StopIteration(3)",
709+
"f caught StopIteration(StopIteration(3))",
709710
])
710711

712+
@unittest.skipIf(sys.version_info.minor < 7, "Requires Python 3.7+")
711713
def test_send_and_return_with_value(self):
712714
"""
713715
Test send and return with value
@@ -742,17 +744,17 @@ def g(r):
742744
"f sending spam to g",
743745
"g received 'spam'",
744746
"g returning 1",
745-
'f caught StopIteration(1,)',
747+
'f caught StopIteration(1)',
746748
'g starting',
747749
'f sending spam to g',
748750
"g received 'spam'",
749751
'g returning (2,)',
750-
'f caught StopIteration((2,),)',
752+
'f caught StopIteration((2,))',
751753
'g starting',
752754
'f sending spam to g',
753755
"g received 'spam'",
754-
'g returning StopIteration(3,)',
755-
'f caught StopIteration(StopIteration(3,),)'
756+
'g returning StopIteration(3)',
757+
'f caught StopIteration(StopIteration(3))'
756758
])
757759

758760
# def test_catching_exception_from_subgen_and_returning(self):

graalpython/com.oracle.graal.python.test/src/tests/test_zlib.py

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2018, 2019, Oracle and/or its affiliates.
1+
# Copyright (c) 2018, 2020, Oracle and/or its affiliates.
22
# Copyright (C) 1996-2017 Python Software Foundation
33
#
44
# Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
@@ -122,26 +122,6 @@ def check_big_decompress_buffer(self, size, decompress_func):
122122
finally:
123123
data = None
124124

125-
def assertRaisesRegex(self, expected_exception, expected_regex, function,
126-
*args, **kwargs):
127-
"""Asserts that the message in a raised exception matches a regex.
128-
129-
Args:
130-
expected_exception: Exception class expected to be raised.
131-
expected_regex: Regex (re.Pattern object or string) expected
132-
to be found in error message.
133-
args: Function to be called and extra positional args.
134-
kwargs: Extra kwargs.
135-
msg: Optional message used in case of failure. Can only be used
136-
when assertRaisesRegex is used as a context manager.
137-
"""
138-
try:
139-
function(*args, **kwargs)
140-
except expected_exception as e:
141-
if not re.compile(expected_regex).search(str(e)):
142-
assert False, "exception message '%r' does not match '%r'" % (e, expected_regex)
143-
else:
144-
assert False, "expected '%r' to raise '%r'" % (self.function, exc_type)
145125

146126
class CompressTests(BaseCompressTestCase, unittest.TestCase):
147127
# Test compression in one go (whole message compression)

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/array/ArrayBuiltins.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2017, 2019, Oracle and/or its affiliates.
2+
* Copyright (c) 2017, 2020, Oracle and/or its affiliates.
33
* Copyright (c) 2014, Regents of the University of California
44
*
55
* All rights reserved.
@@ -54,6 +54,7 @@
5454
import com.oracle.graal.python.builtins.objects.common.SequenceStorageNodes;
5555
import com.oracle.graal.python.builtins.objects.common.SequenceStorageNodes.GenNodeSupplier;
5656
import com.oracle.graal.python.builtins.objects.common.SequenceStorageNodes.GeneralizationNode;
57+
import com.oracle.graal.python.builtins.objects.type.TypeNodes;
5758
import com.oracle.graal.python.nodes.SpecialMethodNames;
5859
import com.oracle.graal.python.nodes.function.PythonBuiltinBaseNode;
5960
import com.oracle.graal.python.nodes.function.PythonBuiltinNode;
@@ -203,7 +204,12 @@ String str(PArray self) {
203204
typeCode = "d";
204205
array = Arrays.toString(((DoubleSequenceStorage) sequenceStorage).getInternalDoubleArray());
205206
}
206-
return String.format("array('%s', %s)", typeCode, array);
207+
String typeName = TypeNodes.GetNameNode.doSlowPath(self.getLazyPythonClass());
208+
if (sequenceStorage.length() == 0) {
209+
return String.format("%s('%s')", typeName, typeCode);
210+
} else {
211+
return String.format("%s('%s', %s)", typeName, typeCode, array);
212+
}
207213
}
208214
}
209215

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/bytes/ByteArrayBuiltins.java

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2017, 2019, Oracle and/or its affiliates.
2+
* Copyright (c) 2017, 2020, Oracle and/or its affiliates.
33
* Copyright (c) 2014, Regents of the University of California
44
*
55
* All rights reserved.
@@ -44,7 +44,6 @@
4444
import static com.oracle.graal.python.nodes.SpecialMethodNames.__REPR__;
4545
import static com.oracle.graal.python.nodes.SpecialMethodNames.__RMUL__;
4646
import static com.oracle.graal.python.nodes.SpecialMethodNames.__SETITEM__;
47-
import static com.oracle.graal.python.nodes.SpecialMethodNames.__STR__;
4847
import static com.oracle.graal.python.runtime.exception.PythonErrorType.SystemError;
4948
import static com.oracle.graal.python.runtime.exception.PythonErrorType.TypeError;
5049
import static com.oracle.graal.python.runtime.exception.PythonErrorType.ValueError;
@@ -65,6 +64,7 @@
6564
import com.oracle.graal.python.builtins.objects.range.PRange;
6665
import com.oracle.graal.python.builtins.objects.slice.PSlice;
6766
import com.oracle.graal.python.builtins.objects.tuple.PTuple;
67+
import com.oracle.graal.python.builtins.objects.type.TypeNodes;
6868
import com.oracle.graal.python.nodes.SpecialMethodNames;
6969
import com.oracle.graal.python.nodes.call.special.LookupAndCallUnaryNode;
7070
import com.oracle.graal.python.nodes.control.GetIteratorExpressionNode.GetIteratorNode;
@@ -333,21 +333,13 @@ public Object mul(Object self, Object other) {
333333
public abstract static class RMulNode extends MulNode {
334334
}
335335

336-
@Builtin(name = __STR__, minNumOfPositionalArgs = 1)
337-
@GenerateNodeFactory
338-
public abstract static class StrNode extends PythonUnaryBuiltinNode {
339-
@Specialization
340-
public Object str(PByteArray self) {
341-
return self.toString();
342-
}
343-
}
344-
345336
@Builtin(name = __REPR__, minNumOfPositionalArgs = 1)
346337
@GenerateNodeFactory
347338
public abstract static class ReprNode extends PythonUnaryBuiltinNode {
348339
@Specialization
349-
public Object repr(PByteArray self) {
350-
return self.toString();
340+
public Object repr(PByteArray self, @Cached("create()") TypeNodes.GetNameNode getNameNode) {
341+
String typeName = getNameNode.execute(self.getLazyPythonClass());
342+
return self.formatByteArray(typeName);
351343
}
352344
}
353345

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/bytes/PByteArray.java

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2017, 2019, Oracle and/or its affiliates.
2+
* Copyright (c) 2017, 2020, Oracle and/or its affiliates.
33
* Copyright (c) 2014, Regents of the University of California
44
*
55
* All rights reserved.
@@ -69,11 +69,16 @@ public final void setSequenceStorage(SequenceStorage store) {
6969
@Override
7070
@TruffleBoundary
7171
public String toString() {
72-
if (store instanceof ByteSequenceStorage) {
73-
byte[] barr = ((ByteSequenceStorage) store).getInternalByteArray();
74-
return String.format("bytearray(%s)", BytesUtils.bytesRepr(barr, barr.length));
72+
return formatByteArray("bytearray");
73+
}
74+
75+
@TruffleBoundary
76+
public String formatByteArray(String typeName) {
77+
if (getSequenceStorage() instanceof ByteSequenceStorage) {
78+
byte[] barr = ((ByteSequenceStorage) getSequenceStorage()).getInternalByteArray();
79+
return String.format("%s(%s)", typeName, BytesUtils.bytesRepr(barr, barr.length));
7580
} else {
76-
return String.format("bytearray(%s)", store);
81+
return String.format("%s(%s)", typeName, getSequenceStorage());
7782
}
7883
}
7984

0 commit comments

Comments
 (0)