| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import unittest |
| 4 |
|
| 5 |
from mypy.test.helpers import assert_string_arrays_equal |
| 6 |
from mypyc.codegen.emit import Emitter, EmitterContext, ReturnHandler |
| 7 |
from mypyc.codegen.emitwrapper import generate_arg_check |
| 8 |
from mypyc.ir.rtypes import int_rprimitive, list_rprimitive |
| 9 |
from mypyc.namegen import NameGenerator |
| 10 |
|
| 11 |
|
| 12 |
class TestArgCheck(unittest.TestCase): |
| 13 |
def setUp(self) -> None: |
| 14 |
self.context = EmitterContext(NameGenerator([["mod"]]), True) |
| 15 |
|
| 16 |
def test_check_list(self) -> None: |
| 17 |
emitter = Emitter(self.context) |
| 18 |
generate_arg_check("x", list_rprimitive, emitter, ReturnHandler("NULL")) |
| 19 |
lines = emitter.fragments |
| 20 |
self.assert_lines( |
| 21 |
[ |
| 22 |
"PyObject *arg_x;", |
| 23 |
"if (likely(PyList_Check(obj_x)))", |
| 24 |
" arg_x = obj_x;", |
| 25 |
"else {", |
| 26 |
' CPy_TypeError("list", obj_x);', |
| 27 |
" return NULL;", |
| 28 |
"}", |
| 29 |
], |
| 30 |
lines, |
| 31 |
) |
| 32 |
|
| 33 |
def test_check_int(self) -> None: |
| 34 |
emitter = Emitter(self.context) |
| 35 |
generate_arg_check("x", int_rprimitive, emitter, ReturnHandler("NULL")) |
| 36 |
generate_arg_check("y", int_rprimitive, emitter, ReturnHandler("NULL"), optional=True) |
| 37 |
lines = emitter.fragments |
| 38 |
self.assert_lines( |
| 39 |
[ |
| 40 |
"CPyTagged arg_x;", |
| 41 |
"if (likely(PyLong_Check(obj_x)))", |
| 42 |
" arg_x = CPyTagged_BorrowFromObject(obj_x);", |
| 43 |
"else {", |
| 44 |
' CPy_TypeError("int", obj_x); return NULL;', |
| 45 |
"}", |
| 46 |
"CPyTagged arg_y;", |
| 47 |
"if (obj_y == NULL) {", |
| 48 |
" arg_y = CPY_INT_TAG;", |
| 49 |
"} else if (likely(PyLong_Check(obj_y)))", |
| 50 |
" arg_y = CPyTagged_BorrowFromObject(obj_y);", |
| 51 |
"else {", |
| 52 |
' CPy_TypeError("int", obj_y); return NULL;', |
| 53 |
"}", |
| 54 |
], |
| 55 |
lines, |
| 56 |
) |
| 57 |
|
| 58 |
def assert_lines(self, expected: list[str], actual: list[str]) -> None: |
| 59 |
actual = [line.rstrip("\n") for line in actual] |
| 60 |
assert_string_arrays_equal(expected, actual, "Invalid output") |