Advertisement
Guest User

Untitled

a guest
Jan 27th, 2018
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.87 KB | None | 0 0
  1. E IntegrityError: (IntegrityError) duplicate key value violates unique constraint "ix_users_email"
  2. E DETAIL: Key (email)=(not_used@example.com) already exists.
  3. E 'INSERT INTO users (email, username, name, role_id, company_id, password_hash, confirmed, member_since, last_seen) VALUES (%(email)s, %(username)s, %(name)s, %(role_id)s, %(company_id)s, %(password_hash)s, %(confirmed)s, %(member_since)s, %(last_seen)s) RETURNING users.id' {'username': 'not_used', 'confirmed': True, 'name': 'To be Removed', 'member_since': datetime.datetime(2014, 10, 29, 19, 19, 41, 7929), 'company_id': None, 'role_id': 3, 'last_seen': datetime.datetime(2014, 10, 29, 19, 19, 41, 7941), 'email': 'not_used@example.com', 'password_hash': 'pbkdf2:sha1:1000$cXUh6GbJ$6f38242871cff5e4cce4c1dc49a62c4aea4ba1f3'}
  4.  
  5. @pytest.yield_fixture(scope='session')
  6. def app():
  7. app = create_app('testing')
  8. app.config['SERVER_NAME'] = 'example.com:1234'
  9. ctx = app.app_context()
  10. ctx.push()
  11. app.response_class = TestResponse
  12. app.test_client_class = TestClient
  13. yield app
  14. ctx.pop()
  15.  
  16.  
  17. @pytest.fixture(scope='session')
  18. def db(app):
  19. _db.drop_all()
  20. _db.create_all()
  21.  
  22. Permission.insert_initial()
  23. Role.insert_initial()
  24. Technology.insert_initial()
  25. Product.insert_initial()
  26. Actor.insert_initial()
  27. Industry.insert_initial()
  28. DeliveryCategory.insert_initial()
  29. DeliveryMethod.insert_initial()
  30.  
  31. user = User(email='admin@example.com', username='admin', confirmed=True, password='admin', name='Admin')
  32. user.role = Role.query.filter_by(name='Administrator').first()
  33. _db.session.add(user)
  34. _db.session.commit()
  35.  
  36. return _db
  37.  
  38.  
  39. @pytest.yield_fixture(scope='function')
  40. def session(db):
  41. db.session.begin_nested()
  42. yield db.session
  43. db.session.rollback()
  44.  
  45.  
  46. @pytest.yield_fixture(scope='function')
  47. def user(session):
  48. yield session.query(User).filter_by(email='admin@example.com').first()
  49.  
  50.  
  51. @pytest.yield_fixture(scope='function')
  52. def client(app, user):
  53. client = app.test_client()
  54. client.auth = 'Basic ' + b64encode((user.email + ':' + 'admin').encode('utf-8')).decode('utf-8')
  55. yield client
  56.  
  57. def test_edit_agenda_add_company_rep_without_company(session, client, user):
  58. user2 = User(name='To be Removed', password='not_used', username='not_used', confirmed=True,
  59. email='not_used@example.com', role=Role.query.filter_by(name='User').first())
  60. agenda = Agenda(name='Invalid Company Rep', creator=user)
  61. session.add(agenda)
  62. session.commit()
  63.  
  64. response = client.jput('/api/v1.0/agendas/%s' % agenda.id,
  65. data={
  66. 'company_representative': user2.id
  67. }
  68. )
  69. assert response.status_code == 200
  70.  
  71. def test_edit_agenda_add_user_already_in_agenda(session, client, user):
  72. user2 = User(name='To be Removed', password='not_used', username='not_used', confirmed=True,
  73. email='not_used@example.com', role=Role.query.filter_by(name='User').first())
  74. agenda = Agenda(name='Invalid Company Rep', creator=user)
  75. agenda.users.append(user2)
  76. session.add(agenda)
  77. session.commit()
  78.  
  79. response = client.jput('/api/v1.0/agendas/%s' % agenda.id,
  80. data={
  81. 'users': [user2.id]
  82. }
  83. )
  84. assert response.status_code == 200
  85.  
  86. def test_get_agenda_modules_where_agenda_that_does_not_exist(session, app):
  87. # Create admin user with permission to create models
  88. user = User(email='admin2@example.com', username='admin2', confirmed=True, password='admin2')
  89. user.role = Role.query.filter_by(name='Administrator').first()
  90. session.add(user)
  91. session.commit()
  92.  
  93. client = app.test_client()
  94. client.auth = 'Basic ' + b64encode(
  95. (user.email + ':' + 'admin2').encode('utf-8')).decode('utf-8')
  96. response = client.jget('/api/v1.0/agenda-modules/%s/%s' % (5, 4))
  97. assert response.status_code == 404
  98.  
  99. def test_get_agenda_modules_agenda_modules_does_not_exist(session, app):
  100. agenda = Agenda(name='Is tired in the AM')
  101. session.add(agenda)
  102.  
  103. # Create admin user with permission to create models
  104. user = User(email='admin2@example.com', username='admin2', confirmed=True, password='admin2')
  105. user.role = Role.query.filter_by(name='Administrator').first()
  106. session.add(user)
  107. session.commit()
  108.  
  109. client = app.test_client()
  110. client.auth = 'Basic ' + b64encode(
  111. (user.email + ':' + 'admin2').encode('utf-8')).decode('utf-8')
  112. response = client.jget('/api/v1.0/agenda-modules/%s/%s' % (agenda.id, 4))
  113. assert response.status_code == 400
  114. assert response.jdata['message'] == 'AgendaModule does not exist.'
  115.  
  116. @pytest.yield_fixture(scope='function')
  117. def session(db):
  118. ...
  119. session = db.create_scoped_session(options={'bind':connection})
  120. ...
  121.  
  122. class SessionWithBinds(SignallingSession):
  123. """The extends the flask-sqlalchemy signalling session so that we may
  124. provide our own 'binds' argument.
  125. """
  126.  
  127. def __init__(self, db, autocommit=False, autoflush=True, **options):
  128. #: The application that this session belongs to.
  129. self.app = db.get_app()
  130. self._model_changes = {}
  131. #: A flag that controls whether this session should keep track of
  132. #: model modifications. The default value for this attribute
  133. #: is set from the ``SQLALCHEMY_TRACK_MODIFICATIONS`` config
  134. #: key.
  135. self.emit_modification_signals =
  136. self.app.config['SQLALCHEMY_TRACK_MODIFICATIONS']
  137. bind = options.pop('bind', None) or db.engine
  138. # Our changes to allow a 'binds' argument
  139. try:
  140. binds = options.pop('binds')
  141. except KeyError:
  142. binds = db.get_binds(self.app)
  143. SessionBase.__init__(self, autocommit=autocommit, autoflush=autoflush,
  144. bind=bind,
  145. binds=binds, **options)
  146.  
  147. class TestFriendlySQLAlchemy(SQLAlchemy):
  148. """For overriding create_session to return our own Session class"""
  149.  
  150. def create_session(self, options):
  151. return SessionWithBinds(self, **options)
  152.  
  153. db = TestFriendlySQLAlchemy()
  154.  
  155. @pytest.yield_fixture(scope='function')
  156. def session(db):
  157. ...
  158. session = db.create_scoped_session(options={'bind':connection, 'binds':None})
  159. ...
  160.  
  161. @pytest.yield_fixture(scope='function')
  162. def session(db):
  163. db.session.begin_nested()
  164. yield db.session
  165. db.session.rollback()
  166.  
  167. # module conftest.py
  168. import pytest
  169.  
  170. from app import create_app
  171. from app import db as _db
  172. from sqlalchemy import event
  173. from sqlalchemy.orm import sessionmaker
  174.  
  175. @pytest.fixture(scope="session")
  176. def app(request):
  177. """
  178. Returns session-wide application.
  179. """
  180. return create_app("testing")
  181.  
  182.  
  183. @pytest.fixture(scope="session")
  184. def db(app, request):
  185. """
  186. Returns session-wide initialised database.
  187. """
  188. with app.app_context():
  189. _db.drop_all()
  190. _db.create_all()
  191.  
  192.  
  193. @pytest.fixture(scope="function", autouse=True)
  194. def session(app, db, request):
  195. """
  196. Returns function-scoped session.
  197. """
  198. with app.app_context():
  199. conn = _db.engine.connect()
  200. txn = conn.begin()
  201.  
  202. options = dict(bind=conn, binds={})
  203. sess = _db.create_scoped_session(options=options)
  204.  
  205. # establish a SAVEPOINT just before beginning the test
  206. # (http://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#using-savepoint)
  207. sess.begin_nested()
  208.  
  209. @event.listens_for(sess(), 'after_transaction_end')
  210. def restart_savepoint(sess2, trans):
  211. # Detecting whether this is indeed the nested transaction of the test
  212. if trans.nested and not trans._parent.nested:
  213. # The test should have normally called session.commit(),
  214. # but to be safe we explicitly expire the session
  215. sess2.expire_all()
  216.  
  217. _db.session = sess
  218. yield sess
  219.  
  220. # Cleanup
  221. sess.remove()
  222. # This instruction rollsback any commit that were executed in the tests.
  223. txn.rollback()
  224. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement