Exemplo n.º 1
0
    def test_should_keep_as_is_when_patch(self, find_one_mock, update_mock):

        db_product = Product("Nome do BD", ["cat1", "cat2"], 9.00, "URL do BD",
                             "ID do BD")

        find_one_mock.return_value = db_product

        product = Product(
            None,
            [],
            5.00,
            None,
            "IDfdasiofsdaoifmiosdafa",
        )

        products_service.update_product(product, True)
        find_one_mock.assert_called_once()
        update_mock.assert_called_with(mock.ANY)
        name, args, kwargs = update_mock.mock_calls[0]

        update_product: Product = args[0]
        self.assertEqual(db_product.name, update_product.name)
        self.assertEqual(product.categories, update_product.categories)
        self.assertEqual(product.price, update_product.price)
        self.assertEqual(db_product.url, update_product.url)
        self.assertEqual(db_product.id, update_product.id)
def __copy_product_ignoring_null(origin_product: Product,
                                 destiny_product: Product) -> None:
    if origin_product.name is not None:
        destiny_product.name = origin_product.name
    if origin_product.categories is not None:
        destiny_product.categories = origin_product.categories
    if origin_product.price is not None:
        destiny_product.price = origin_product.price
    if origin_product.url is not None:
        destiny_product.url = origin_product.url
Exemplo n.º 3
0
    def test_should_add_id_when_product_is_new(self, insert_mock):

        product = Product(None, None, None, None, None)

        products_service.create_product(product)
        self.assertTrue(product.id is not None)
        insert_mock.assert_called_once()
Exemplo n.º 4
0
    def test_should_keep_as_is_when_update(self, find_one_mock, update_mock):

        product = Product("Teste", [], 5.00, "Teste123",
                          "IDfdasiofsdaoifmiosdafa")

        products_service.update_product(product, False)
        find_one_mock.assert_called_once()
        update_mock.assert_called_with(product)
Exemplo n.º 5
0
def _pay_cart_with_balance(carts):
    user = request.user
    money = 0
    name = ''

    for each in carts:
        pd = Product.find(each['product_id'])
        money += pd.price * each['num']
        if name:
            name = '%s,%sx%s' % (name, pd.name, each['num'])
        else:
            name = '%sx%s' % (pd.name, each['num'])

    if user.balance >= money:
        for each in carts:
            ct = Cart(**each)
            ct.state = Cart.State.FINISHED
            ct.save()

        order = Order(uid=user.id,
                      name=name,
                      balance=-money,
                      type=Order.Type.PAY)
        order.set_order_id()
        order.state = Order.State.FINISHED
        resp = order.save(return_keys=[Order.PKEY])
        order = Order.find(resp[Order.PKEY])

        user.balance -= money
        user.save()
        return Response(data=order.to_dict()).out()
    elif user.openid:
        order = Order(uid=user.id,
                      name=name,
                      money=user.balance - money,
                      balance=-user.balance,
                      type=Order.Type.PAY)
        order.set_order_id()
        resp = order.save(return_keys=[Order.PKEY])
        order = Order.find(resp[Order.PKEY])

        wxorder = WXOrder(user, order)
        tokens = wxorder.get_token()
        if not tokens:
            return Response(code=ResponseCode.OPERATE_ERROR,
                            msg='订单生成失败').out()

        return Response(code=ResponseCode.LOW_BALANCE,
                        msg='余额不足',
                        data={
                            'need_money': money - user.balance,
                            'order_id': order.id,
                            'order': tokens
                        }).out()
    else:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
Exemplo n.º 6
0
def cart():
    carts = Cart.query(fetchone=False,
                       uid=request.user.id,
                       state=Cart.State.INIT)
    resp = []
    for each in carts:
        pd = Product.find(each['product_id'])
        cart = Cart(**each).to_dict()
        cart['product_name'] = pd.name
        cart['product_price'] = pd.price
        cart['product_icon'] = pd.icon
        resp.append(cart)
    return str(Response(data=resp))
Exemplo n.º 7
0
def _pay_cart_with_coupon(carts):
    user = request.user

    if user.is_founder():
        discount = 0.4
    elif user.is_cofounder():
        discount = 0.3
    else:
        discount = 0.2

    money = 0
    name = ''
    for each in carts:
        pd = Product.find(each['product_id'])
        money += pd.price * each['num']
        if name:
            name = '%s,%sx%s' % (name, pd.name, each['num'])
        else:
            name = '%sx%s' % (pd.name, each['num'])

    discount_money = min(user.coupon, int(money * discount))
    need_money = money - discount_money

    if user.openid:
        order = Order(uid=user.id,
                      name=name,
                      money=-need_money,
                      coupon=-discount_money,
                      type=Order.Type.PAY)
        order.set_order_id()
        resp = order.save(return_keys=[Order.PKEY])
        order = Order.find(resp[Order.PKEY])

        wxorder = WXOrder(user, order)
        tokens = wxorder.get_token()
        if not tokens:
            return str(Response(code=ResponseCode.OPERATE_ERROR, msg='订单生成失败'))

        return str(
            Response(code=ResponseCode.LOW_BALANCE,
                     msg='余额不足',
                     data={
                         'need_money': need_money,
                         'order_id': order.id,
                         'order': tokens
                     }))
    else:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
Exemplo n.º 8
0
def add_cart():
    product_id = request.form['product_id']
    if not product_id or not Product.find(product_id):
        return str(Response(code=ResponseCode.DATA_NOT_EXIST, msg='商品不存在'))

    cart = Cart.query_instance(uid=request.user.id,
                               product_id=product_id,
                               state=Cart.State.INIT)
    if cart:
        cart.num += 1
    else:
        cart = Cart()
        cart.uid = request.user.id
        cart.product_id = product_id
    ct = cart.save(return_keys=[Cart.PKEY])
    cart = Cart.find(ct[Cart.PKEY])

    return Response(data=cart.to_dict()).out()
Exemplo n.º 9
0
def _buy_product_with_balance(product_id):
    pd = Product.find(product_id)
    user = request.user

    if user.balance >= pd.price:
        order = Order(uid=user.id,
                      name=pd.name,
                      money=user.balance - pd.price,
                      balance=-user.balance,
                      type=Order.Type.PAY)
        order.set_order_id()
        order.save()

        user.balance -= pd.price
        user.save()

        return Response(data=pd.to_dict()).out()
    elif user.openid:
        order = Order(uid=user.id,
                      name=pd.name,
                      money=user.balance - pd.price,
                      balance=-user.balance,
                      type=Order.Type.PAY)
        order.set_order_id()
        order.save()

        order = WXOrder(user, order)

        tokens = order.get_token()
        if not tokens:
            return Response(code=ResponseCode.OPERATE_ERROR,
                            msg='订单生成失败').out()

        return Response(code=ResponseCode.LOW_BALANCE,
                        msg='余额不足',
                        data={
                            'need_money': pd.price - user.balance,
                            'order': tokens
                        }).out()
    else:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
Exemplo n.º 10
0
def _buy_product_with_coupon(product_id):
    pd = Product.find(product_id)
    user = request.user
    if user.is_founder():
        discount = 0.4
    elif user.is_cofounder():
        discount = 0.3
    else:
        discount = 0.2

    discount_money = min(user.coupon, int(pd.price * discount))
    need_money = pd.price - discount_money

    if user.openid:
        order = Order(uid=user.id,
                      name=pd.name,
                      money=-need_money,
                      coupon=-discount_money,
                      type=Order.Type.PAY)
        order.set_order_id()
        order.save()

        wxorder = WXOrder(user, order)
        tokens = wxorder.get_token()
        if not tokens:
            return str(Response(code=ResponseCode.OPERATE_ERROR, msg='订单生成失败'))

        return str(
            Response(code=ResponseCode.LOW_BALANCE,
                     msg='余额不足',
                     data={
                         'need_money': need_money,
                         'order': tokens
                     }))
    else:
        return str(Response(code=ResponseCode.AUTH_REQUIRED, msg='请微信关注服务号'))
Exemplo n.º 11
0
class ProductsApiServerTest(unittest.TestCase):

    DEFAULT_RESPONSE_DICT = Response()
    #     {
    #     status_code: 000,
    #     "body": {}
    # }
    DEFAULT_AUTH_TOKEN = "eyJraWQiOiJubEtjQ1JMXC94SVdYc3ljODZFSzhHaXQ0ekhlUFpIYW9Ha2RIMTF5K3pmST0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZjQ4N2U3Ni01NzdhLTRhNDgtOGI0Yi05ZTRiZjM3NzVlYmIiLCJhdWQiOiIyaHE4MTNkOHRpbnVzbTRwaWY5YnYwaTR1OSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJldmVudF9pZCI6IjJiOTUzZjM1LTljZjAtNDViMi1iYWJjLTNhODhlZGY1MmQwMiIsInRva2VuX3VzZSI6ImlkIiwiYXV0aF90aW1lIjoxNTcyMjU2OTM4LCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtZWFzdC0xLmFtYXpvbmF3cy5jb21cL3VzLWVhc3QtMV9Qb3dmRVdON3AiLCJjb2duaXRvOnVzZXJuYW1lIjoiZ3VpbGhlcm1lZ2luZXpzaWx2YSIsImV4cCI6MTU3MjI2MDUzOCwiaWF0IjoxNTcyMjU2OTM5LCJlbWFpbCI6Imd1aWxoZXJtZWdpbmV6c2lsdmFAZ21haWwuY29tIn0.s4n08YI9KUkuF3DYRWKgT_y4i2AUi7gGfo-GA8J_gxQJhlRi4T4g8nQgTgDUy9pAWTbs_a6ELlSL7Vec9GvDtmKV47k7mbSC-_DFNhbds7v2n22W3KYfc7P_mx97cKqhImmj0x5nhaTES22ogOstFF9EjjtRwxwEyh9ZSXG08ymwkxoP3cKAzy1-QrN5Ew61ZqCnifyzqUbmYe8-rhT-xvkaVRhoqUsVHkxu5-w2YV9UE-4KGsVLRqfsvG1GlBgcSZc4_5IhsOmzy0odl4CHgrQe_mspJ8kZikCG6ZWe-mTwpSZx4tEAxcQlMHRK93qJ5BaUik1r3FnWtJIZPdyy9w"

    DEFAULT_PRODUCT_ID = "60dd920c-e1ef-4afe-894a-f04ef3c116c8"
    DEFAULT_PRODUCT_NAME = "5PRODUCT TEST"
    DEFAULT_PRODUCT_PRICE = 6.99
    DEFAULT_PRODUCT_URL = "5PRODUCT-TESTfdasfdasfahgfhgfdhfgdhdfghgfdhfdghfgdhfdghfdghfdghfdghfdghdf"
    DEFAULT_PRODUCT_CATEGORIES = ["eletrônicos",
                                   "utensílios",
                                   "cama e mesa",
                                   "cozinha",
                                   "higiene pessoal",
                                   "abobrinha"
                                  ]

    DEFAULT_UPDATE_PRODUCT_NAME = "5PRODUCT TEST2"
    DEFAULT_UPDATE_PRODUCT_CATEGORIES = ["eletrônicos",
                                   "utensílios",
                                   "cama e mesa",
                                   "abobrinha"
                                  ]
    DEFAULT_UPDATE_PRODUCT_PRICE = 10.0
    DEFAULT_UPDATE_PRODUCT_URL = "5PRODUCT-TEST2fdasfdasfahgfhgfdhfgdhdfghgfdhfdghfgdhfdghfdghfdghfdghfdghdf"

    DEFAULT_2_PRODUCTS_ARRAY: [] = [
        Product(
            DEFAULT_PRODUCT_NAME,
            DEFAULT_PRODUCT_CATEGORIES,
            DEFAULT_PRODUCT_PRICE,
            DEFAULT_PRODUCT_URL,
            DEFAULT_PRODUCT_ID
        ),
        Product(
            DEFAULT_PRODUCT_NAME,
            DEFAULT_PRODUCT_CATEGORIES,
            DEFAULT_PRODUCT_PRICE,
            DEFAULT_PRODUCT_URL,
            DEFAULT_PRODUCT_ID
        )
    ]

    DEFAULT_INVALID_PRODUCT_CREATE_DTO = ProductCreateDto()
    DEFAULT_INVALID_PRODUCT_CREATE_DTO.name = ""
    DEFAULT_INVALID_PRODUCT_CREATE_DTO.categories = ["CAT1", "cozinha"]
    DEFAULT_INVALID_PRODUCT_CREATE_DTO.price = 1.0
    DEFAULT_INVALID_PRODUCT_CREATE_DTO.url = "sgfsdgsd"

    DEFAULT_PRODUCT_CREATE_DTO = ProductCreateDto()
    DEFAULT_PRODUCT_CREATE_DTO.name = DEFAULT_PRODUCT_NAME
    DEFAULT_PRODUCT_CREATE_DTO.categories = DEFAULT_PRODUCT_CATEGORIES
    DEFAULT_PRODUCT_CREATE_DTO.price = DEFAULT_PRODUCT_PRICE
    DEFAULT_PRODUCT_CREATE_DTO.url = DEFAULT_PRODUCT_URL

    DEFAULT_PRODUCT_UPDATE_DTO = ProductUpdateDto()
    DEFAULT_PRODUCT_UPDATE_DTO.name = DEFAULT_UPDATE_PRODUCT_NAME
    DEFAULT_PRODUCT_UPDATE_DTO.categories = DEFAULT_UPDATE_PRODUCT_CATEGORIES
    DEFAULT_PRODUCT_UPDATE_DTO.price = DEFAULT_UPDATE_PRODUCT_PRICE
    DEFAULT_PRODUCT_UPDATE_DTO.url = DEFAULT_UPDATE_PRODUCT_URL

    DEFAULT_INVALID_PRODUCT_UPDATE_DTO = ProductCreateDto()
    DEFAULT_INVALID_PRODUCT_UPDATE_DTO.name = ""
    DEFAULT_INVALID_PRODUCT_UPDATE_DTO.categories = ["CAT2", "utensílios"]
    DEFAULT_INVALID_PRODUCT_UPDATE_DTO.price = 1.0
    DEFAULT_INVALID_PRODUCT_UPDATE_DTO.url = "sgfsdgsd"

    DEFAULT_PRODUCT_PATCH_DTO = ProductPatchDto()
    DEFAULT_PRODUCT_PATCH_DTO.name = None
    DEFAULT_PRODUCT_PATCH_DTO.categories = DEFAULT_UPDATE_PRODUCT_CATEGORIES
    DEFAULT_PRODUCT_PATCH_DTO.price = DEFAULT_UPDATE_PRODUCT_PRICE
    DEFAULT_PRODUCT_PATCH_DTO.url = None

    DEFAULT_INVALID_PRODUCT_PATCH_DTO = ProductCreateDto()
    DEFAULT_INVALID_PRODUCT_PATCH_DTO.name = ""
    DEFAULT_INVALID_PRODUCT_PATCH_DTO.categories = ["CAT2", "utensílios"]
    DEFAULT_INVALID_PRODUCT_PATCH_DTO.price = 1.0
    DEFAULT_INVALID_PRODUCT_PATCH_DTO.url = "sgfsdgsd"

    DEFAULT_INVALID_PRODUCT_PATCH_NO_NAME_WITH_URL_DTO = ProductCreateDto()
    DEFAULT_INVALID_PRODUCT_PATCH_NO_NAME_WITH_URL_DTO.categories = ["CAT2", "utensílios"]
    DEFAULT_INVALID_PRODUCT_PATCH_NO_NAME_WITH_URL_DTO.price = 1.0
    DEFAULT_INVALID_PRODUCT_PATCH_NO_NAME_WITH_URL_DTO.url = "sgfsdgsd"

    DEFAULT_AUTH_USER = AuthUser("b9225de5-3090-48c5-9200-94f8039384ff", "*****@*****.**")

    @patch('app.products_service.delete_product', autospec=True)
    @patch('app.products_service.update_product', autospec=True)
    @patch('app.products_service.create_product', autospec=True)
    @patch('app.products_service.get_product', autospec=True)
    @patch('app.products_service.get_products', autospec=True)
    @patch('app.security.cognito_auth.verify_token', autospec=True)
    def test_should_get_contraint_exception_when_constraints_fails(
            self,
            verify_token_mock,
            get_products_mock,
            get_product_mock,
            create_product_mock,
            update_product_mock,
            delete_product_mock
    ):
        verify_token_mock.return_value = copy.deepcopy(self.DEFAULT_AUTH_USER)

        expected_exception = exceptions.get(exceptions.FIELD_CONSTRAINT_VIOLATION_EXCEPTION)

        exception_json_body = products_api_server.get_product(
            None,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEquals(expected_exception.code, exception_json_body["errorCode"])
        self.assertEquals(1, len(exception_json_body["validationErrors"]))

        exception_json_body = products_api_server.get_product(
            "fdasfasmdfmsafas",
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEquals(expected_exception.code, exception_json_body["errorCode"])
        self.assertEquals(1, len(exception_json_body["validationErrors"]))

        dto = copy.deepcopy(self.DEFAULT_INVALID_PRODUCT_CREATE_DTO)
        exception_json_body = products_api_server.create_product(
            dto,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(expected_exception.code, exception_json_body["errorCode"])
        self.assertEquals(4, len(exception_json_body["validationErrors"]))

        dto = copy.deepcopy(self.DEFAULT_INVALID_PRODUCT_UPDATE_DTO)
        exception_json_body = products_api_server.update_product(
            self.DEFAULT_PRODUCT_ID,
            dto,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(expected_exception.code, exception_json_body["errorCode"])
        self.assertEquals(4, len(exception_json_body["validationErrors"]))

        dto = copy.deepcopy(self.DEFAULT_INVALID_PRODUCT_PATCH_DTO)
        exception_json_body = products_api_server.update_product(
            self.DEFAULT_PRODUCT_ID,
            dto,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(expected_exception.code, exception_json_body["errorCode"])
        self.assertEquals(4, len(exception_json_body["validationErrors"]))

        dto = copy.deepcopy(self.DEFAULT_INVALID_PRODUCT_PATCH_NO_NAME_WITH_URL_DTO)
        exception_json_body = products_api_server.update_product(
            self.DEFAULT_PRODUCT_ID,
            dto,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(expected_exception.code, exception_json_body["errorCode"])
        self.assertEquals(1, len(exception_json_body["validationErrors"]))

        exception_json_body = products_api_server.delete_product(
            None,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(expected_exception.code, exception_json_body["errorCode"])
        self.assertEquals(1, len(exception_json_body["validationErrors"]))


    @patch('app.products_service.delete_product', autospec=True)
    @patch('app.products_service.update_product', autospec=True)
    @patch('app.products_service.create_product', autospec=True)
    @patch('app.products_service.get_product', autospec=True)
    @patch('app.products_service.get_products', autospec=True)
    @patch('app.security.cognito_auth.verify_token', autospec=True)
    def test_should_get_authentication_exception_response_when_authentication_fails(
            self,
            verify_token_mock,
            get_products_mock,
            get_product_mock,
            create_product_mock,
            update_product_mock,
            delete_product_mock

    ):
        verify_token_mock.return_value = copy.deepcopy(self.DEFAULT_AUTH_USER)
        exception = exceptions.get(exceptions.USER_NOT_AUTHORIZED_EXCEPTION)

        get_products_mock.side_effect = exception
        get_product_mock.side_effect = exception
        create_product_mock.side_effect = exception
        update_product_mock.side_effect = exception
        delete_product_mock.side_effect = exception

        exception_json_body = products_api_server.get_all_products(
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(exception.code, exception_json_body["errorCode"])

        exception_json_body = products_api_server.get_product(
            self.DEFAULT_PRODUCT_ID,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(exception.code, exception_json_body["errorCode"])

        exception_json_body = products_api_server.create_product(
            self.DEFAULT_PRODUCT_CREATE_DTO,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(exception.code, exception_json_body["errorCode"])

        exception_json_body = products_api_server.update_product(
            self.DEFAULT_PRODUCT_ID,
            self.DEFAULT_PRODUCT_UPDATE_DTO,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(exception.code, exception_json_body["errorCode"])

        exception_json_body = products_api_server.patch_product(
            self.DEFAULT_PRODUCT_ID,
            self.DEFAULT_PRODUCT_PATCH_DTO,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(exception.code, exception_json_body["errorCode"])

        exception_json_body = products_api_server.delete_product(
            self.DEFAULT_PRODUCT_ID,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEqual(exception.code, exception_json_body["errorCode"])

    @patch('app.products_service.get_products', autospec=True)
    @patch('app.security.cognito_auth.verify_token', autospec=True)
    def test_should_get_all_products_when_products_available(self, verify_token_mock, get_products_mock):

        verify_token_mock.return_value = copy.deepcopy(self.DEFAULT_AUTH_USER)
        get_products_mock.return_value = copy.deepcopy(self.DEFAULT_2_PRODUCTS_ARRAY)

        products: [] = products_api_server.get_all_products(
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )

        for i in range(len(products)):
            self.assertEqual(self.DEFAULT_2_PRODUCTS_ARRAY[i].name, products[i].name)
            self.assertEqual(self.DEFAULT_2_PRODUCTS_ARRAY[i].categories, products[i].categories)
            self.assertEqual(self.DEFAULT_2_PRODUCTS_ARRAY[i].price, products[i].price)
            self.assertEqual(self.DEFAULT_2_PRODUCTS_ARRAY[i].url, products[i].url)

    @patch('app.products_service.get_product', autospec=True)
    @patch('app.security.cognito_auth.verify_token', autospec=True)
    def test_should_get_product_when_product_exists(self, verify_token_mock, get_products_mock):

        verify_token_mock.return_value = copy.deepcopy(self.DEFAULT_AUTH_USER)
        get_products_mock.return_value = copy.deepcopy(self.DEFAULT_2_PRODUCTS_ARRAY[0])

        product: Product = products_api_server.get_product(
            self.DEFAULT_PRODUCT_ID,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )

        self.assertEqual(self.DEFAULT_2_PRODUCTS_ARRAY[0].name, product.name)
        self.assertEqual(self.DEFAULT_2_PRODUCTS_ARRAY[0].categories, product.categories)
        self.assertEqual(self.DEFAULT_2_PRODUCTS_ARRAY[0].price, product.price)
        self.assertEqual(self.DEFAULT_2_PRODUCTS_ARRAY[0].url, product.url)

    @patch('app.products_service.get_product', autospec=True)
    @patch('app.security.cognito_auth.verify_token', autospec=True)
    def test_should_get_product_when_method_is_called(self, verify_token_mock, get_products_mock):

        verify_token_mock.return_value = copy.deepcopy(self.DEFAULT_AUTH_USER)

        exception = exceptions.get(exceptions.PRODUCT_NOT_FOUND_EXCEPTION)
        get_products_mock.side_effect = exception

        exception_json_body = products_api_server.get_product(
            self.DEFAULT_PRODUCT_ID,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )
        self.assertEquals(exception.code, exception_json_body["errorCode"])

    @patch('app.products_service.create_product', autospec=True)
    @patch('app.security.cognito_auth.verify_token', autospec=True)
    def test_should_create_product_when_product_is_ok(self, verify_token_mock, create_product_mock):

        verify_token_mock.return_value = copy.deepcopy(self.DEFAULT_AUTH_USER)
        create_product_mock.return_value = None

        products_api_server.create_product(
            self.DEFAULT_PRODUCT_CREATE_DTO,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )

        create_product_mock.assert_called_once()

    @patch('app.products_service.update_product', autospec=True)
    @patch('app.security.cognito_auth.verify_token', autospec=True)
    def test_should_update_product_when_product_is_ok(self, verify_token_mock, update_product_mock):
        verify_token_mock.return_value = copy.deepcopy(self.DEFAULT_AUTH_USER)
        update_product_mock.return_value = None

        products_api_server.update_product(
            self.DEFAULT_PRODUCT_ID,
            self.DEFAULT_PRODUCT_UPDATE_DTO,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )

        update_product_mock.assert_called_once()

    @patch('app.products_service.update_product', autospec=True)
    @patch('app.security.cognito_auth.verify_token', autospec=True)
    def test_should_patch_product_when_product_is_ok(self, verify_token_mock, update_product_mock):
        verify_token_mock.return_value = copy.deepcopy(self.DEFAULT_AUTH_USER)
        update_product_mock.return_value = None

        products_api_server.patch_product(
            self.DEFAULT_PRODUCT_ID,
            self.DEFAULT_PRODUCT_PATCH_DTO,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )

        update_product_mock.assert_called_once()

    @patch('app.products_service.delete_product', autospec=True)
    @patch('app.security.cognito_auth.verify_token', autospec=True)
    def test_should_delete_product_when_product_is_ok(self, verify_token_mock, delete_product_mock):
        verify_token_mock.return_value = copy.deepcopy(self.DEFAULT_AUTH_USER)
        delete_product_mock.return_value = None

        products_api_server.delete_product(
            self.DEFAULT_PRODUCT_ID,
            self.DEFAULT_RESPONSE_DICT,
            self.DEFAULT_AUTH_TOKEN
        )

        delete_product_mock.assert_called_once()
 def post(self):
     data = request.get_json()
     product = Product(**data)
     model = self.__dao.create(product)
     return self.verify_sql_error(model)
Exemplo n.º 13
0
def product(product_id=0):
    product = Product.find(product_id)
    return Response(data=product.to_dict()).out()
Exemplo n.º 14
0
def products():
    shop_id = request.args.get('shop_id', Shop.GEHUA)
    products = Product.query(fetchone=False, shop_id=shop_id) or []
    return Response(data=[Product(**each).to_dict()
                          for each in products]).out()
Exemplo n.º 15
0
 def parse_to_product(self) -> Product:
     return Product(self.name, self.categories, self.price, self.url)
def create_product(product: Product) -> None:
    product.id = str(uuid.uuid4())
    products_dao.insert(product)
 def put(self, uuid):
     data = request.get_json()
     product = Product(**data)
     product.id = uuid
     model = self.__dao.update(product)
     return self.verify_sql_error(model)