Skip to content
Advertisement

Mocking sqlobject function call for test db

I am trying to mock sqlbuilder.func for test cases with pytest

I successfully mocked sqlbuilder.func.TO_BASE64 with correct output but when I tried mocking sqlbuilder.func.FROM_UNIXTIME I didn’t get any error but the resulted output is incorrect with the generated query. Below is the minimal working example of the problem.

models.py

JavaScript

conftest.py

JavaScript

test_ex1.py

JavaScript

Current SQL:

JavaScript

Expected SQL:

JavaScript

Edit Example

JavaScript

Advertisement

Answer

By default, sqlbuilder.func is an SQLExpression that passes its attribute (sqlbuilder.func.datetime, e.g.) to the SQL backend as a constant (sqlbuilder.func actually is an alias for sqlbuilder.ConstantSpace). See the docs about SQLExpression, the FAQ and the code for func.

When you mock an attribute in func namespace it’s evaluated by SQLObject and passed to the backend in reduced form. If you want to return a string literal from the mocking function you need to tell SQLObject it’s a value that has to be passed to the backend as is, unevaluated. The way to do it is to wrap the literal in SQLConstant like this:

JavaScript

See SQLConstant.

The entire test script now looks this

JavaScript

The output is:

JavaScript

PS. Full disclosure: I’m the current maintainer of SQLObject.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement