Skip to content

Commit

Permalink
Adding several test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
sripathikrishnan committed Oct 24, 2016
1 parent c4159fe commit e78b375
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 17 deletions.
2 changes: 1 addition & 1 deletion jinja2sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def __init__(self, env=None):
if env:
self.env = env
else:
self.env = Environment(autoescape=False)
self.env = Environment()
self._prepare_environment()

def _prepare_environment(self):
Expand Down
74 changes: 58 additions & 16 deletions test_jinja2sql.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,73 @@
import unittest
from jinja2sql import JinjaSql

source = """
{% macro print_where() -%}
WHERE
{%- endmacro %}
SELECT project, timesheet, hours
FROM timesheet
{{ print_where() | sqlsafe }} project_id = {{request.project_id}}
and user_id = {{session.user_id | upper}}
"""

data = {
_DATA = {
"etc": {
"columns": "project, timesheet, hours",
"lt": "<",
"gt": ">",

},
"request": {
"project_id": 123
"project_id": 123,
},
"session": {
"user_id": "sripathi"
"user_id": u"sripathi"
}
}

class JinjaSqlTest(unittest.TestCase):
def test_bind_params(self):
source = """
SELECT project, timesheet, hours
FROM timesheet
WHERE project_id = {{request.project_id}}
and user_id = {{ session.user_id }}
"""
j = JinjaSql()
query, bind_params = j.prepare_query(source, _DATA)
self.assertEquals(bind_params, [123, u'sripathi'])

def test_sqlsafe(self):
source = """SELECT {{etc.columns | sqlsafe}} FROM timesheet"""
j = JinjaSql()
query, bind_params = j.prepare_query(source, _DATA)
self.assertEquals(query, "SELECT project, timesheet, hours FROM timesheet")

def test_macro(self):
source = """
{% macro OPTIONAL_AND(condition, expression, value) -%}
{%- if condition -%}AND {{expression | sqlsafe}} {{value}} {%- endif-%}
{%- endmacro -%}
SELECT 'x' from dual
WHERE 1=1
{{ OPTIONAL_AND(request.project_id != -1,
"project_id = ", request.project_id) | sqlsafe }}
{{ OPTIONAL_AND(request.unknown_column,
"some_column = ", request.unknown_column) | sqlsafe -}}
AND fixed_column = {{session.user_id}}
"""

expected_query = """
SELECT 'x' from dual
WHERE 1=1
AND project_id = %s
AND fixed_column = %s"""

j = JinjaSql()
query, bind_params = j.prepare_query(source, _DATA)

self.assertEquals(query.strip(), query.strip())
self.assertEquals(bind_params, [123, u'sripathi'])


def test_html_escape(self):
"""Check that jinja doesn't escape HTML characters"""

source = """select 'x' from dual where X {{etc.lt | sqlsafe}} 1"""
j = JinjaSql()
query, bind_params = j.prepare_query(source, data)
print query
print bind_params
query, bind_params = j.prepare_query(source, _DATA)
self.assertEquals(query, "select 'x' from dual where X < 1")

if __name__ == '__main__':
unittest.main()

0 comments on commit e78b375

Please sign in to comment.