Skip to content

Commit 81f72ce

Browse files
committed
Initialize repository
0 parents  commit 81f72ce

File tree

4 files changed

+77
-0
lines changed

4 files changed

+77
-0
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.cache/
2+
.venv/
3+
4+
__pycache__/
5+
*.pyc

setup.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from setuptools import setup, Extension
2+
3+
4+
setup(
5+
name='monkeypatch',
6+
ext_modules=[
7+
Extension('monkeypatch', sources=[
8+
'src/monkeypatch.c',
9+
]),
10+
],
11+
)

src/monkeypatch.c

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include "Python.h"
2+
3+
static PyObject *monkeypatch(PyObject *self, PyObject *args) {
4+
PyObject *target;
5+
PyObject *attr_name;
6+
PyObject *attr_val;
7+
8+
if(!PyArg_ParseTuple(args, "OOO", &target, &attr_name, &attr_val))
9+
return NULL;
10+
11+
_PyObject_GenericSetAttrWithDict(target, attr_name, attr_val, NULL);
12+
13+
Py_RETURN_NONE;
14+
}
15+
16+
struct PyMethodDef methods[] = {
17+
{ "monkeypatch", monkeypatch, METH_VARARGS, "" },
18+
{ 0 },
19+
};
20+
21+
struct PyModuleDef module = {
22+
.m_base = PyModuleDef_HEAD_INIT,
23+
.m_name = "monkeypatch",
24+
.m_doc = "",
25+
.m_size = 0,
26+
.m_methods = methods,
27+
};
28+
29+
PyMODINIT_FUNC PyInit_monkeypatch(void) {
30+
PyModule_Create(&module);
31+
}

test/test_monkeypatch.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import pytest
2+
from monkeypatch import monkeypatch
3+
4+
5+
def test_monkeypatch_hello():
6+
with pytest.raises(TypeError):
7+
str.hello = "world"
8+
monkeypatch(str, "hello", "world")
9+
assert str.hello == "world"
10+
11+
12+
def test_monkeypatch_str():
13+
def rev_up(self):
14+
return self[::-1].upper()
15+
monkeypatch(str, "rev_up", rev_up)
16+
assert "abc".rev_up() == "CBA"
17+
18+
19+
def test_monkeypatch_int():
20+
def upto(self, value):
21+
return tuple(range(self, value + 1))
22+
monkeypatch(int, "upto", upto)
23+
assert (1).upto(10) == (1,2,3,4,5,6,7,8,9,10)
24+
25+
26+
def test_monkeypatch_tuple():
27+
def mult_by(self, value):
28+
return tuple(x * value for x in self)
29+
monkeypatch(tuple, "mult_by", mult_by)
30+
assert (1,2,3).mult_by(10) == (10,20,30)

0 commit comments

Comments
 (0)