def test_rolls_back_uncommitted_work_by_default(session_factory): uow = unit_of_work.ProductSqlAlchemyUnitOfWork(session_factory) with uow: insert_batch(uow.session, 'batch1', 'MEDIUM-PLINTH', 100, None) new_session = session_factory() rows = list(new_session.execute('SELECT * FROM batches')) assert rows == []
def sqlite_bus(sqlite_session_factory): bus = bootstrap.bootstrap( start_orm=True, uow=unit_of_work.ProductSqlAlchemyUnitOfWork(sqlite_session_factory), send_mail=lambda *args: None, publish=lambda *args: None, ) yield bus clear_mappers
def try_to_allocate(orderid, sku, exceptions): line = model.OrderLine(orderid, sku, 10) try: with unit_of_work.ProductSqlAlchemyUnitOfWork() as uow: product = uow.products.get(sku=sku) product.allocate(line) time.sleep(0.2) uow.commit() except Exception as e: print(traceback.format_exc()) exceptions.append(e)
def test_rolls_back_on_error(session_factory): class MyException(Exception): pass uow = unit_of_work.ProductSqlAlchemyUnitOfWork(session_factory) with pytest.raises(MyException): with uow: insert_batch(uow.session, 'batch1', 'LARGE-FORK', 100, None) raise MyException() new_session = session_factory() rows = list(new_session.execute('SELECT * FROM "batches"')) assert rows == []
def handle_change_batch_quantity(m): try: logging.info('handling %s', m) print('handling %s', m) data = json.loads(m['data']) cmd = commands.ChangeBatchQuantity(ref=data['batchref'], qty=data['qty']) MessageBus().handle(cmd, uow=unit_of_work.ProductSqlAlchemyUnitOfWork()) except Exception as e: logging.info(str(e)) return None
def bootstrap(start_orm: bool = True, uow: unit_of_work.AbstractUnitOfWork = unit_of_work.ProductSqlAlchemyUnitOfWork(), notifications: AbstractNotifications = EmailNotification(), publish: Callable = redis_eventpublisher.publish, ) -> MessageBus: if start_orm: print('vai gerar a base de dados: ', config.get_postgres_uri()) orm.start_mappers() dependencies = {'uow': uow, 'send_mail': notifications, 'publish': publish} inject_event_handlers = { event_type: [ inject_dependencies(handler, dependencies) for handler in event_handlers ] for event_type, event_handlers in handlers.EVENT_HANDLERS.items() } inject_command_handlers = { command_type: inject_dependencies(handler, dependencies) for command_type, handler in handlers.COMMAND_HANDLERS.items() } """ inject_event_handlers = { events.Allocated: [ lambda e: handlers.publish_allocated_event(e, publish), lambda e: handlers.add_allocation_to_read_model(e, uow), ], events.Deallocated: [ lambda e: handlers.remove_allocation_from_read_model(e, uow), lambda e: handlers.reallocate(e, uow), ], events.OutOfStock: [ lambda e: handlers.send_out_of_stock_notification(e, send_mail), ] } inject_command_handlers = { commands.Allocate: lambda c: handlers.allocate(c, uow), commands.CreateBatch: lambda c: handlers.add_batch(c, uow), commands.ChangeBatchQuantity: lambda c: handlers.change_batch_quantity(c, uow), } """ return MessageBus( uow=uow, event_handlers=inject_event_handlers, command_handlers=inject_command_handlers, )
def get_by_ref(): try: uow = unit_of_work.ProductSqlAlchemyUnitOfWork(get_session) command = commands.GetProductByRef(request.json['ref']) product = MessageBus().handle(command, uow) return_object = {} if product[0] is not None: return_object = { "sku": product[0].sku, "version_number": product[0].version_number } return json.dumps({"product": return_object}, indent=3), 200 except Exception as e: return jsonify({'message': str(e)}), 400
def list_products(): try: uow = unit_of_work.ProductSqlAlchemyUnitOfWork(get_session) command = commands.GetProducts(request.json['sku']) products = MessageBus().handle(command, uow) return_products = [] if products is not None and len(products) > 0: return_products = [{ "sku": p.sku, "version_number": p.version_number } for p in products[0]] return json.dumps({"products": return_products}, indent=3), 200 except Exception as e: return jsonify({'message': str(e)}), 400
def list_batches(): try: uow = unit_of_work.ProductSqlAlchemyUnitOfWork(get_session) command = commands.GetBaches(request.json['ref']) product = MessageBus().handle(command, uow) batches = [] if product[0] is not None: batches = [{ "reference": v.reference, "sku": v.sku, "purchased_quantity": v._purchased_quantity } for v in product[0]] return json.dumps({"batches": batches}, indent=3), 200 except Exception as e: return jsonify({'message': str(e)}), 400
def allocate_endpoint(): try: #command = commands.Allocate.from_json(request.json) command = commands.Allocate( request.json['orderid'], request.json['sku'], request.json['qty'], ) results = MessageBus().handle( command, unit_of_work.ProductSqlAlchemyUnitOfWork(get_session)) batchref = results.pop(0) except (OutOfStock, InvalidSku, Exception) as e: return jsonify({'message': str(e)}), 400 return jsonify({'batchref': batchref}), 202
def list_order_lines(): try: uow = unit_of_work.ProductSqlAlchemyUnitOfWork(get_session) command = commands.GetOrderLines(" ") order_lines = MessageBus().handle(command, uow) return_list = [] if order_lines is not None and len(order_lines) > 0: return_list = [{ "orderid": o.orderid, "sku": o.sku, "qty": o.qty } for o in order_lines[0]] return json.dumps({"order_lines": return_list}, indent=3), 200 except Exception as e: return jsonify({'message': str(e)}), 400
def test_uow_can_retrieve_a_batch_and_allocate_to_it(session_factory): sku = 'HIPSTER-WORKBENCH' session = session_factory() batch = insert_batch(session, 'batch1', sku, 100, None) insert_product(session, sku, [batch], version_number=1) session.commit() uow = unit_of_work.ProductSqlAlchemyUnitOfWork(session_factory) with uow: product = uow.products.get(sku=sku) line = model.OrderLine('o1', sku, 10) product.allocate(line) uow.commit() batchref = get_allocated_batch_ref(session, 'o1', sku) assert batchref == 'batch1'
def test_uow_can_save_product_and_batch_and_allocate_it(session_factory): uow = unit_of_work.ProductSqlAlchemyUnitOfWork(session_factory) session = session_factory() sku = 'HIPSTER-WORKBENCH3' with uow: product = model.Product(sku, [model.Batch('b3', sku, 100, None)]) uow.products.add(product) # product.batches.append() prodcut2 = uow.products.get_by_batchref('b3') product = uow.products.get(sku=sku) line = model.OrderLine('o3', sku, 10) product.allocate(line) uow.commit() batchref = get_allocated_batch_ref(session, 'o3', sku) assert batchref == 'b3'
def allocations_view_endpoint(orderid): uow = unit_of_work.ProductSqlAlchemyUnitOfWork(get_session) result = views.allocations(orderid, uow) if not result: return jsonify({'message': 'order not found'}), 404 return jsonify(result), 200
def test_list_baches(session_factory): uow = unit_of_work.ProductSqlAlchemyUnitOfWork(session_factory) with uow: batches = uow.products.list_batches() assert batches == []