Testing process will inevitably have to construct test data, if the data is a single, relatively simple, but if it is bulk data, more trouble.
Recently seen Factory_boy this python third-party library that supports a class by SQLAlchemyModelFactory SQLAlchemy model, simply try a bit, feeling quite easy to use.
Dependencies:
factory-boy==2.12.0 sqlalchemy==1.3.7 mysql-connector-python==8.0.17
user table (mysql):
1 CREATE TABLE `user` ( 2 `id` int(11) NOT NULL, 3 `name` varchar(20) DEFAULT NULL, 4 PRIMARY KEY (`id`) 5 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';
boytest.py
1 from sqlalchemy import Column,String, Integer, Unicode, create_engine 2 from sqlalchemy.ext.declarative import declarative_base 3 from sqlalchemy.orm import scoped_session, sessionmaker 4 5 Base = declarative_base() 6 7 class User(Base): 8 # 表的名字: 9 __tablename__ = 'user' 10 11 # 表的结构: 12 id = Column(String(20), primary_key=True) 13 name = Column(String(20)) 14 15 engine = create_engine('mysql+mysqlconnector://autotest:[email protected]:3306/testdb') 16 DBSession = scoped_session(sessionmaker(bind=engine))#这里需要使用scoped_session 17 18 #Base.metadata.create_all(engine) #创建表 19 20 import factory 21 22 class UserFactory(factory.alchemy.SQLAlchemyModelFactory): 23 class Meta: 24 model = User 25 sqlalchemy_session = DBSession # the SQLAlchemy session object 26 sqlalchemy_session_persistence="commit" #"commit"--perform a session commit() #'flush'-- perform a session flush() 27 28 id = factory.Sequence(lambda n: n) 29 #id = 9 30 name = factory.Sequence(lambda n: u'User %d' % n) 31 32 #清除表内容 33 DBSession.query(User).delete() 34 #DBSession.query(User).filter(User.id==0).delete() 35 DBSession.commit() 36 37 [ 38 is # Users = DBSession.query (the User) .all () 39 # for usr in Users: 40 # Print (usr .__ dict__ magic) 41 is 42 is # Create a record 43 is UserFactory () 44 is # UserFactory () 45 # Create 100 record 46 is factory.build_batch (UserFactory, 100 ) 47 # DBSession.commit () 48 Users = DBSession.query (the User) .all () 49 for usr in Users: 50 Print (. usr the __dict__ ) 51 is print(len(users)) 52 DBSession.remove()
result:
factory.build_batch (UserFactory, 100) which is inserted into line 100 to achieve the record, is very convenient.
References:
https://www.cnblogs.com/wangtaobiu/p/11007547.html
https://blog.csdn.net/zhyh1435589631/article/details/51549944
https://www.liaoxuefeng.com/wiki/897692888725344 / 955,081,460,091,040
https://factoryboy.readthedocs.io/en/latest/orms.html#sqlalchemy