Skip to content

Commit ad0a001

Browse files
committed
Add sql injection test.
1 parent dca0494 commit ad0a001

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

test/test_sql_injection.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import pytest
2+
3+
from mybatis import Mybatis
4+
from mybatis import ConnectionFactory
5+
6+
@pytest.fixture(scope="function")
7+
def db_connection():
8+
connection = ConnectionFactory.get_connection(
9+
dbms_name='postgresql',
10+
host="localhost",
11+
user="mybatis",
12+
password="mybatis",
13+
database="mybatis"
14+
)
15+
connection.start_transaction()
16+
cursor = connection.cursor()
17+
cursor.execute("DROP TABLE IF EXISTS fruits")
18+
create_table_sql1 = '''CREATE TABLE IF NOT EXISTS fruits (
19+
id SERIAL PRIMARY KEY,
20+
name VARCHAR(100),
21+
category VARCHAR(100),
22+
price int)
23+
'''
24+
create_table_sql2 = '''CREATE TABLE IF NOT EXISTS users (
25+
id SERIAL PRIMARY KEY,
26+
name VARCHAR(100),
27+
password VARCHAR(100))
28+
'''
29+
# 在测试开始前准备数据
30+
cursor.execute(create_table_sql1)
31+
cursor.execute(create_table_sql2)
32+
cursor.execute("INSERT INTO fruits (name, category, price) VALUES ('Alice', 'A', 100)")
33+
cursor.execute("INSERT INTO fruits (name, category, price) VALUES ('Bob', 'B', 200)")
34+
cursor.execute("INSERT INTO users (name, password) VALUES ('Bob', 'B')")
35+
connection.commit()
36+
37+
# 提供数据库连接给测试用例
38+
yield connection
39+
40+
# 清理数据和关闭连接
41+
connection.close()
42+
43+
def test_sql_injection1(db_connection):
44+
mb = Mybatis(db_connection, "mapper", cache_memory_limit=50*1024*1024)
45+
46+
@mb.SelectMany("SELECT name, category, price FROM fruits WHERE name = #{name}")
47+
def select_fruit(name):
48+
pass
49+
50+
ret = select_fruit(name="'OR '1'='1")
51+
assert ret is None
52+
53+
ret = select_fruit(name="OR '1'='1'")
54+
assert ret is None
55+
56+
def test_sql_injection2(db_connection):
57+
mb = Mybatis(db_connection, "mapper", cache_memory_limit=50*1024*1024)
58+
59+
@mb.SelectMany("SELECT name, category, price FROM fruits WHERE name = #{name}")
60+
def select_fruit(name):
61+
pass
62+
63+
ret = select_fruit(name=" '' UNION SELECT name, password, 1 FROM users")
64+
assert ret is None

0 commit comments

Comments
 (0)