Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ def __index__(self):
return self.value

class BuiltinTest(unittest.TestCase):
def test_build_class_checks_body_arguments(self):
def body(required):
pass

with self.assertRaises(TypeError):
__build_class__(body, "", "")

def test_bin(self):
self.assertEqual(bin(0), '0b0')
self.assertEqual(bin(1), '0b1')
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# The Universal Permissive License (UPL), Version 1.0
Expand Down Expand Up @@ -39,9 +39,13 @@

import unittest
import csv
import re
from tempfile import TemporaryFile

class TestUnicodeCharacters(unittest.TestCase):
def test_builtin_type_as_dialect(self):
self.assertIsInstance(csv.reader(re.ASCII, int), type(csv.reader([])))

def test_read_utf_32_delimiter(self):
test_data = ['a\U0001F642b']
reader = csv.reader(test_data, delimiter="\U0001F642")
Expand Down Expand Up @@ -77,4 +81,3 @@ def test_write_utf32_field_with_utf32_delimiter(self):




Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,21 @@ def test_fromtimestamp(self):
with self.assertRaisesRegex(OverflowError, "timestamp out of range for platform time_t"):
datetime.date.fromtimestamp(1e200)

def test_fromtimestamp_before_importing_time(self):
proc = subprocess.run(
[
sys.executable,
"-c",
"import datetime\n"
"datetime.date.fromtimestamp(0)\n"
"datetime.datetime.fromtimestamp(0)\n",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
self.assertEqual(proc.returncode, 0, proc.stderr)


def test_fromisocalendar(self):
with self.assertRaisesRegex(ValueError, "Year is out of range: -1"):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@

class HashlibTest(unittest.TestCase):

def test_new_validates_type(self):
self.assertRaises(TypeError, hashlib.sha3_224.__new__)
self.assertRaises(TypeError, hashlib.sha3_224.__new__, '')
self.assertRaises(TypeError, hashlib.sha3_224.__new__, int)

def test_messagedigest_update_after_digest(self):
sha1 = hashlib.sha1()
sha1.update(b'a')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,11 @@ def test_invalid_return_statement():
assert_raise_syntax_error("return 10", "'return' outside function")
assert_raise_syntax_error("class A: return 10\n", "'return' outside function")


def test_top_level_async_with():
assert_raise_syntax_error("async with _:\n pass", "'async with' outside async function")


def test_outside_of_loop_errors():
assert_raise_syntax_error("break", "'break' outside loop")
# TODO: parser gives invalid syntax for this one, but should be: "'break' outside loop"
Expand Down
3 changes: 3 additions & 0 deletions graalpython/com.oracle.graal.python.test/src/tests/test_re.py
Original file line number Diff line number Diff line change
Expand Up @@ -1411,6 +1411,9 @@ def test_flags(self):
self.assertEqual(re.compile('(?u)').flags, re.UNICODE)
self.assertEqual(re.compile('(?x)').flags, re.VERBOSE | re.UNICODE)

with self.assertRaisesRegex(ValueError, "cannot use LOCALE flag with a str pattern"):
re.compile('A', 9999)


def test_groups(self):
# returns number of capturing groups in the pattern
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@


class SignalTests(unittest.TestCase):
def test_getsignal_rejects_invalid_number(self):
with self.assertRaisesRegex(ValueError, "signal number out of range"):
signal.getsignal(0)

def test_args_validation(self):
try:
import _signal
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# The Universal Permissive License (UPL), Version 1.0
Expand Down Expand Up @@ -57,6 +57,11 @@ def test_sleep_sec():
assert time.time() - start > 1


def test_mktime_requires_tuple():
with unittest.TestCase().assertRaisesRegex(TypeError, "Tuple or struct_time argument required"):
time.mktime(sum)


def test_monotonic():
times = [time.monotonic() for _ in range(100)]
for t1, t2 in zip(times[:-1], times[1:]):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@
import com.oracle.graal.python.nodes.SpecialAttributeNames;
import com.oracle.graal.python.nodes.SpecialMethodNames;
import com.oracle.graal.python.nodes.StringLiterals;
import com.oracle.graal.python.nodes.argument.CreateArgumentsNode;
import com.oracle.graal.python.nodes.argument.ReadArgumentNode;
import com.oracle.graal.python.nodes.attributes.GetFixedAttributeNode;
import com.oracle.graal.python.nodes.attributes.ReadAttributeFromModuleNode;
Expand Down Expand Up @@ -2265,6 +2266,7 @@ protected Object doItNonFunction(VirtualFrame frame, Object function, Object[] a
@Cached PyMappingCheckNode pyMappingCheckNode,
@Cached CallNode callPrep,
@Cached CallNode callType,
@Cached CreateArgumentsNode createArguments,
@Cached CallDispatchers.FunctionCachedInvokeNode invokeBody,
@Cached UpdateBasesNode update,
@Cached PyObjectSetItem setOrigBases,
Expand Down Expand Up @@ -2356,9 +2358,11 @@ class InitializeBuildClass {
if (!pyMappingCheckNode.execute(inliningTarget, ns)) {
throw raiseNoMapping(init.isClass, init.meta, ns);
}
Object[] bodyArguments = PArguments.create(0);
PFunction bodyFunction = (PFunction) function;
Object[] bodyArguments = createArguments.execute(inliningTarget, bodyFunction, PythonUtils.EMPTY_OBJECT_ARRAY, PKeyword.EMPTY_KEYWORDS,
bodyFunction.getCode().getSignature(), null, null, bodyFunction.getDefaults(), bodyFunction.getKwDefaults(), false);
PArguments.setSpecialArgument(bodyArguments, ns);
invokeBody.execute(frame, inliningTarget, (PFunction) function, bodyArguments);
invokeBody.execute(frame, inliningTarget, bodyFunction, bodyArguments);
if (init.bases != basesArray) {
setOrigBases.execute(frame, inliningTarget, ns, SpecialAttributeNames.T___ORIG_BASES__, PFactory.createTuple(language, basesArray));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ public final class SignalModuleBuiltins extends PythonBuiltins {
private static final int ITIMER_VIRTUAL = 1;
private static final int ITIMER_PROF = 2;
private static final TruffleString T_ITIMER_ERROR = tsLiteral("ItimerError");
private static final TruffleString T_SIGNAL_NUMBER_OUT_OF_RANGE = tsLiteral("signal number out of range");

public static final String J_DEFAULT_INT_HANDLER = "default_int_handler";
public static final TruffleString T_DEFAULT_INT_HANDLER = tsLiteral(J_DEFAULT_INT_HANDLER);
Expand Down Expand Up @@ -336,7 +337,11 @@ private static Object handlerToPython(SignalHandler handler, int signum, ModuleD
abstract static class GetSignalNode extends PythonBinaryClinicBuiltinNode {
@Specialization
@TruffleBoundary
static Object getsignal(PythonModule mod, int signum) {
static Object getsignal(PythonModule mod, int signum,
@Bind Node inliningTarget) {
if (!Signals.isValidSignal(signum)) {
throw PRaiseNode.raiseStatic(inliningTarget, PythonErrorType.ValueError, T_SIGNAL_NUMBER_OUT_OF_RANGE);
}
ModuleData data = mod.getModuleState(ModuleData.class);
return handlerToPython(Signals.getCurrentSignalHandler(signum), signum, data);
}
Expand Down Expand Up @@ -616,7 +621,11 @@ public void handle(sun.misc.Signal arg0) {
}

static String signalNumberToName(int signum) {
return signum > SIGMAX ? "INVALID SIGNAL" : SIGNAL_NAMES[signum];
return isValidSignal(signum) ? SIGNAL_NAMES[signum] : "INVALID SIGNAL";
}

static boolean isValidSignal(int signum) {
return signum > 0 && signum <= SIGMAX && SIGNAL_NAMES[signum] != null;
}

@TruffleBoundary
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,7 @@ private static void setGlobalTimeZone(PythonModule timeModule, PythonLanguage la
timeZone = TimeZone.getTimeZone(tzEnv);
}

// save in the module state
ModuleState moduleState = timeModule.getModuleState(ModuleState.class);
moduleState.currentZoneId = timeZone.toZoneId();
context.setCurrentZoneId(timeZone.toZoneId());

// update time module attributes
TruffleString noDaylightSavingZone = toTruffleStringUncached(timeZone.getDisplayName(false, TimeZone.SHORT));
Expand All @@ -217,20 +215,6 @@ public static double timeSeconds() {
return System.currentTimeMillis() / 1000.0;
}

/**
* Return current time zone (that can be changed with time.tzset()). The only correct way to get
* it.
*/
@TruffleBoundary
public static TimeZone getGlobalTimeZone(PythonContext context) {
PythonModule timeModule = context.lookupBuiltinModule(T_TIME);

ModuleState moduleState = timeModule.getModuleState(ModuleState.class);
ZoneId zoneId = moduleState.currentZoneId;

return TimeZone.getTimeZone(zoneId);
}

private static final int TM_YEAR = 0; /* year */
private static final int TM_MON = 1; /* month */
private static final int TM_MDAY = 2; /* day of the month */
Expand Down Expand Up @@ -368,12 +352,12 @@ Object tzset(PythonModule self) {
public abstract static class PythonLocalTimeNode extends PythonBinaryBuiltinNode {

@Specialization
static PTuple localtime(VirtualFrame frame, PythonModule module, Object seconds,
static PTuple localtime(VirtualFrame frame, @SuppressWarnings("unused") PythonModule module, Object seconds,
@Bind Node inliningTarget,
@Bind PythonContext context,
@Cached ToLongTime toLongTime,
@Bind PythonLanguage language) {
ModuleState moduleState = module.getModuleState(ModuleState.class);
return PFactory.createStructSeq(language, STRUCT_TIME_DESC, getTimeStruct(moduleState.currentZoneId, toLongTime.execute(frame, inliningTarget, seconds)));
return PFactory.createStructSeq(language, STRUCT_TIME_DESC, getTimeStruct(context.getCurrentZoneId(), toLongTime.execute(frame, inliningTarget, seconds)));
}
}

Expand Down Expand Up @@ -982,19 +966,21 @@ private static TimeZone getTimeZone(ZoneId currentZoneId) {
}

@Specialization
static TruffleString formatTime(PythonModule module, TruffleString format, @SuppressWarnings("unused") PNone time,
static TruffleString formatTime(@SuppressWarnings("unused") PythonModule module, TruffleString format, @SuppressWarnings("unused") PNone time,
@Bind Node inliningTarget,
@Bind PythonContext context,
@Shared("byteIndexOfCp") @Cached TruffleString.ByteIndexOfCodePointNode byteIndexOfCodePointNode,
@Shared("ts2js") @Cached ToJavaStringNode toJavaStringNode,
@Shared("js2ts") @Cached TruffleString.FromJavaStringNode fromJavaStringNode,
@Exclusive @Cached PRaiseNode raiseNode) {
ModuleState moduleState = module.getModuleState(ModuleState.class);
return format(toJavaStringNode.execute(format), getIntLocalTimeStruct(moduleState.currentZoneId, (long) timeSeconds()), getTimeZone(moduleState.currentZoneId), fromJavaStringNode);
ZoneId currentZoneId = context.getCurrentZoneId();
return format(toJavaStringNode.execute(format), getIntLocalTimeStruct(currentZoneId, (long) timeSeconds()), getTimeZone(currentZoneId), fromJavaStringNode);
}

@Specialization(guards = "tupleCheckNode.execute(inliningTarget, time)", limit = "1")
static TruffleString formatTime(VirtualFrame frame, PythonModule module, TruffleString format, Object time,
static TruffleString formatTime(VirtualFrame frame, @SuppressWarnings("unused") PythonModule module, TruffleString format, Object time,
@Bind Node inliningTarget,
@Bind PythonContext context,
@SuppressWarnings("unused") @Cached PyTupleCheckNode tupleCheckNode,
@Cached GetTupleStorage getTupleStorage,
@Cached SequenceStorageNodes.GetInternalObjectArrayNode getArray,
Expand All @@ -1004,7 +990,7 @@ static TruffleString formatTime(VirtualFrame frame, PythonModule module, Truffle
@Shared("js2ts") @Cached TruffleString.FromJavaStringNode fromJavaStringNode,
@Exclusive @Cached PRaiseNode raiseNode) {
int[] date = checkStructtime(frame, inliningTarget, getTupleStorage.execute(inliningTarget, time), getArray, asSizeNode, raiseNode);
return format(toJavaStringNode.execute(format), date, getTimeZone(module.getModuleState(ModuleState.class).currentZoneId), fromJavaStringNode);
return format(toJavaStringNode.execute(format), date, getTimeZone(context.getCurrentZoneId()), fromJavaStringNode);
}

@Specialization
Expand All @@ -1027,8 +1013,9 @@ abstract static class MkTimeNode extends PythonBinaryBuiltinNode {

@ExplodeLoop
@Specialization(guards = "tupleCheckNode.execute(inliningTarget, tuple)", limit = "1")
static double mktime(VirtualFrame frame, PythonModule module, Object tuple,
static double mktime(VirtualFrame frame, @SuppressWarnings("unused") PythonModule module, Object tuple,
@Bind Node inliningTarget,
@Bind PythonContext context,
@SuppressWarnings("unused") @Cached PyTupleCheckNode tupleCheckNode,
@Cached GetTupleStorage getTupleStorage,
@Cached PyNumberAsSizeNode asSizeNode,
Expand All @@ -1044,8 +1031,14 @@ static double mktime(VirtualFrame frame, PythonModule module, Object tuple,
for (int i = 0; i < ELEMENT_COUNT; i++) {
integers[i] = asSizeNode.executeExact(frame, inliningTarget, items[i]);
}
ModuleState moduleState = module.getModuleState(ModuleState.class);
return op(moduleState.currentZoneId, integers);
return op(context.getCurrentZoneId(), integers);
}

@Fallback
@SuppressWarnings("unused")
static Object mktime(Object module, Object tuple,
@Bind Node inliningTarget) {
throw PRaiseNode.raiseStatic(inliningTarget, TypeError, ErrorMessages.TUPLE_OR_STRUCT_TIME_ARG_REQUIRED);
}

@TruffleBoundary
Expand All @@ -1061,12 +1054,12 @@ private static long op(ZoneId timeZone, int[] integers) {
public abstract static class CTimeNode extends PythonBinaryBuiltinNode {

@Specialization
public static TruffleString localtime(VirtualFrame frame, PythonModule module, Object seconds,
public static TruffleString localtime(VirtualFrame frame, @SuppressWarnings("unused") PythonModule module, Object seconds,
@Bind Node inliningTarget,
@Bind PythonContext context,
@Cached ToLongTime toLongTime,
@Cached TruffleString.FromJavaStringNode fromJavaStringNode) {
ModuleState moduleState = module.getModuleState(ModuleState.class);
int[] tm = getIntLocalTimeStruct(moduleState.currentZoneId, toLongTime.execute(frame, inliningTarget, seconds));
int[] tm = getIntLocalTimeStruct(context.getCurrentZoneId(), toLongTime.execute(frame, inliningTarget, seconds));
return format(tm, fromJavaStringNode);
}

Expand All @@ -1090,10 +1083,10 @@ public abstract static class ASCTimeNode extends PythonBinaryBuiltinNode {
};

@Specialization
static TruffleString localtime(PythonModule module, @SuppressWarnings("unused") PNone time,
static TruffleString localtime(@SuppressWarnings("unused") PythonModule module, @SuppressWarnings("unused") PNone time,
@Bind PythonContext context,
@Shared("js2ts") @Cached TruffleString.FromJavaStringNode fromJavaStringNode) {
ModuleState moduleState = module.getModuleState(ModuleState.class);
return format(getIntLocalTimeStruct(moduleState.currentZoneId, (long) timeSeconds()), fromJavaStringNode);
return format(getIntLocalTimeStruct(context.getCurrentZoneId(), (long) timeSeconds()), fromJavaStringNode);
}

@Specialization(guards = "tupleCheckNode.execute(inliningTarget, time)", limit = "1")
Expand Down Expand Up @@ -1216,7 +1209,6 @@ public Object strptime(VirtualFrame frame, TruffleString dataString, TruffleStri
}

private static final class ModuleState {
ZoneId currentZoneId;
long timeSlept;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@
import com.oracle.graal.python.builtins.objects.PNone;
import com.oracle.graal.python.builtins.objects.module.PythonModule;
import com.oracle.graal.python.builtins.objects.str.PString;
import com.oracle.graal.python.builtins.objects.type.PythonClass;
import com.oracle.graal.python.builtins.objects.type.TpSlots;
import com.oracle.graal.python.builtins.objects.type.TypeNodes;
import com.oracle.graal.python.lib.PyLongAsIntNode;
Expand Down Expand Up @@ -199,8 +198,8 @@ static Object doStringWithKeywords(VirtualFrame frame, PythonBuiltinClassType cl
quotecharObj, quotingObj, skipinitialspaceObj, strictObj, isTrueNode, pyLongCheckExactNode, pyLongAsIntNode, raiseNode);
}

@Specialization
static Object doDialectClassWithKeywords(VirtualFrame frame, PythonBuiltinClassType cls, PythonClass dialectObj, Object delimiterObj, Object doublequoteObj, Object escapecharObj,
@Specialization(guards = "isPythonClass(dialectObj)")
static Object doDialectClassWithKeywords(VirtualFrame frame, PythonBuiltinClassType cls, Object dialectObj, Object delimiterObj, Object doublequoteObj, Object escapecharObj,
Object lineterminatorObj, Object quotecharObj, Object quotingObj, Object skipinitialspaceObj, Object strictObj,
@Bind Node inliningTarget,
@Exclusive @Cached PyObjectLookupAttr getFirstAttributesNode,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
import com.oracle.graal.python.runtime.ExecutionContext.BoundaryCallContext;
import com.oracle.graal.python.runtime.IndirectCallData;
import com.oracle.graal.python.runtime.IndirectCallData.BoundaryCallData;
import com.oracle.graal.python.runtime.PythonContext;
import com.oracle.graal.python.runtime.object.PFactory;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.dsl.Bind;
Expand Down Expand Up @@ -580,7 +581,7 @@ private static Object fromTimestampBoundary(Object cls, Object timestampObject,
throw PRaiseNode.raiseStatic(inliningTarget, OverflowError, ErrorMessages.TIMESTAMP_OUT_OF_RANGE);
}

TimeZone timeZone = TimeModuleBuiltins.getGlobalTimeZone(getContext(inliningTarget));
TimeZone timeZone = PythonContext.get(inliningTarget).getGlobalTimeZone();
ZoneId zoneId = timeZone.toZoneId();
LocalDate localDate = LocalDate.ofInstant(instant, zoneId);
return DateNodes.SubclassNewNode.executeUncached(cls, localDate.getYear(), localDate.getMonthValue(), localDate.getDayOfMonth());
Expand Down
Loading
Loading