kvesteri/sqlalchemy-utils — pull request #46 by mehcode (2013-10-23 07:11:10+00:00)
Title: Improve render_statement; add engine mocking facilities.

Improved the statement rendering capabilities offered by sqlalchemy-utils and added the ability to create a mock of an engine for testing purposes.

```python
from sqlalchemy_utils import create_mock_engine
import io

# Create a mock engine.
engine = create_mock_engine('sqlite:///:memory:')

# The following will now do... nothing. Clap.
Base.metadata.create_all(engine)

# Create a useful mock engine.
stream = io.StringIO()
engine = create_mock_engine('sqlite:///:memory:', stream)

# The following will now record all operations to the stream as if the stream was a pipe to the database.
Base.metadata.create_all(engine)

# Now stream should contain all the create DDL that would have been sent to the database connection.
```

On top of the base `create_mock_engine`, I also added some utility functions.

```python
from sqlalchemy_utils import render_expression

render_expression('SomeModel.__table__.create(engine)') #=> Create DDL for SomeModel
```

And this black magic that I decided would be fun.

```python
from sqlalchemy_utils import mock_engine
import sqlalchemy as sa

# First, create an engine normally... yada yada

engine = create_engine(...)

# Now.. mock it.

with mock_engine('engine') as stream:

# Now.. every executed statement will get sent to the stream.
Base.metadata.create_all(engine)

# Yes, every one.
engine.execute(SomeModel.__table__.select().where(SomeModel.x == 4))

# Call it "offline mode"
```