Skip to content

Commit

Permalink
new tip
Browse files Browse the repository at this point in the history
  • Loading branch information
bbelderbos committed Jun 14, 2024
1 parent b5d1a58 commit 017f22f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ This file gets generated by [this script](index.py).
## Designpatterns

- [Composition over inheritance](notes/20240509111232.md)
- [Depndency injection use case](notes/20240614172758.md)
- [Repository pattern](notes/20240614165322.md)

## Developer
Expand Down
33 changes: 33 additions & 0 deletions notes/20240614172758.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Depndency injection use case

Having an engine object in module scope can lead to accidentally using your dev database during tests, leading to unwanted data and potential bugs! 🐛😱

One solution = _encapsulation_: inject the db string into your DB class. This way, you can use another isolated DB for testing 🔒📈

```python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

DEFAULT_DB_STRING = "sqlite:///todo.db"

Base = declarative_base()

class DB:
def __init__(self, *, db_string=None):
if db_string is None:
db_string = DEFAULT_DB_STRING
self._engine = create_engine(db_string)
self._Session = sessionmaker(bind=self._engine)
self.session = self._Session()


if __name__ == "__main__":
db = DB()
print(db._engine) # Engine(sqlite:///todo.db)

# but you can Inject in-memory test DB in tests
test_db = DB(db_string="sqlite:///:memory:")
print(test_db._engine) # Engine(sqlite:///:memory:)
```

#designpatterns

0 comments on commit 017f22f

Please sign in to comment.