提供分层工厂
Baluster的Python项目详细描述
这个包裹是干什么的
这个包提供了一种简单的方法来构建应用程序的后台结构。 可以将构建复合根用作资源工厂, 建造一个测试用的夹具工厂。
功能
- Lazy initialisation
- Simple composition and dependency handling
示例-复合根
frombalusterimportBaluster,placeholdersimportpsycopg2classApplicationRoot(Baluster):@placeholders.factorydefdb(self,root):# Will be called at the first use# Will be cached so won't be called againreturnpsycopg2.connect("dbname=test user=postgres")@db.closedef_close_db(self,root,db):db.close()@placeholders.factorydefcr(self,root):returnself.db.cursor()@cr.closedef_close_cr(self,root,cr):cr.close()defmain():approot=ApplicationRoot()withapproot:approot.cr.execute('SELECT * FROM user')# at this point the connection and the cursor has already been closed
示例-异步复合根
frombalusterimportBaluster,placeholdersclassAsyncApplicationRoot(Baluster):@placeholders.factoryasyncdefresource(self,root):# Will be called at the first use# Will be cached so won't be called againreturnawaitsome_aync_resource()@db.closeasyncdef_close_resource(self,root,resource):awaitresource.close()defmain():approot=AsyncApplicationRoot()asyncwithapproot:conn=awaitapproot.resourceawaitconn.operation(...)# at this point the resource has already been closed
示例-用于测试的夹具工厂
frombalusterimportBaluster,placeholdersimportpsycopg2classFixtures(Baluster):@placeholders.factorydefcr(self,root):conn=psycopg2.connect("dbname=test user=postgres")returnconn.cursor()classusers(Baluster):@placeholders.factorydefuser(self,root):root.cr.execute('SELECT * FROM user WHERE id=1')returnUser(root.cr.fetchone())@placeholders.factorydefcustomer(self,root):root.cr.execute('SELECT * FROM customer WHERE id=1')returnCustomer(root.cr.fetchone())classorders(Baluster):@placeholders.factorydefamount(self,root):return100@placeholders.factorydefquantity(self,root):return1@placeholders.factorydeforder(self,root):customer=root.users.customercreated_by=root.users.useramount=self.amount# Fictive order object...returnOrder(customer=customer,created_by=created_by,amount=amount,quantity=quantity)@placeholders.factorydefshipped_order(self,root):order=self.orderorder.mark_shipped()returnorderdeftest_order():# Demonstrate a few use fictive usecase# Creating order with defaultsf=Fixtures()assertf.order.calculated_total_value==100assertf.order.shipping_address==f.users.customer.address# Create new fixtures, but keep some cached dataf2=f.copy('cr','users')# Set some valuef2.order.amount=50f2.order.quantity=3assertf2.order.calculated_total_value==150# Manage different stage of object lifef3=f.copy('cr','users')order=f3.shipped_orderwithpytest.raises(OrderException):order.cancel()# as it is shipped
安装
python目标:>;=3.6
$ pip install baluster
依赖关系
这个包是独立的,只使用python标准库。
开发
pip install -r requirements-dev.txt
这将以开发模式安装包(setup.py development) 以及测试包。 我想达到近100%的测试覆盖率。
测试
pytest
贡献
我真的很欢迎任何评论! 如果你分叉我的代码并创建pull请求,我会很高兴的。 对于批准的拉取请求,flake8必须与所有测试一样通过。