Exemplo n.º 1
0
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(SupplyAPITest, self).setUp()

        self.create_user()
        self.client.login(username='******', password='******')

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supplier2 = Supplier.objects.create(**base_supplier)
        self.supply = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply2.pk)
        self.supply3 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply3.pk)
        self.supply4 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply4.pk)

        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()

        self.employee = Employee(first_name="John", last_name="Smith")
        self.employee.save()
Exemplo n.º 2
0
    def obj_update(self, bundle, **kwargs):
        """
        Updates the supply, the product relationship witht the supplier
        
        Extra suppliers before the parent obj_update method destroys it.
        """
        #Get suppliers data before erased by parent method
        try:
            suppliers = bundle.data['suppliers']
        except KeyError as e:
            try:
                suppliers = [bundle.data['supplier']]
            except KeyError:
                raise

        bundle = super(SupplyResource, self).obj_update(bundle, **kwargs)

        for supplier_data in suppliers:
            supplier = Supplier.objects.get(pk=supplier_data['id'])
            try:
                product = Product.objects.get(supplier=supplier,
                                              supply=bundle.obj)
            except Product.DoesNotExist as e:
                product = Product(supplier=supplier, supply=bundle.obj)
            product = self.hydrate_product(product,
                                           bundle=bundle,
                                           **supplier_data)
            product.save()

        return bundle
Exemplo n.º 3
0
    def obj_update(self, bundle, **kwargs):
        """
        Updates the supply, the product relationship witht the supplier
        
        Extra suppliers before the parent obj_update method destroys it.
        """
        #Get suppliers data before erased by parent method
        try:
            suppliers = bundle.data['suppliers']
        except KeyError as e:
            try: 
                suppliers = [bundle.data['supplier']]
            except KeyError:
                raise

        bundle = super(SupplyResource, self).obj_update(bundle, **kwargs)

        for supplier_data in suppliers:
            supplier = Supplier.objects.get(pk=supplier_data['id'])
            try:
                product = Product.objects.get(supplier=supplier,
                                              supply=bundle.obj)
            except Product.DoesNotExist as e:
                product = Product(supplier=supplier,
                                  supply=bundle.obj)
            product = self.hydrate_product(product, bundle=bundle, **supplier_data)
            product.save()
            
        return bundle
Exemplo n.º 4
0
    def create_product(self, supply, supplier, cost, upc=None):
        """
        Creates a product
        """
        if not isinstance(supply, Supply) and isinstance(supply, dict):
            supply = Supply.objects.get(pk=supply['id'])

        if not isinstance(supplier, Supplier) and isinstance(supplier, dict):
            supplier = Supplier.objects.get(pk=supplier['id'])

        product = Product(supply=supply, supplier=supplier, cost=cost, upc=upc)
        product.save()
        return product
Exemplo n.º 5
0
 def create_product(self, supply, supplier, cost, upc=None):
     """
     Creates a product
     """
     if not isinstance(supply, Supply) and isinstance(supply, dict):
         supply = Supply.objects.get(pk=supply['id'])
     
     if not isinstance(supplier, Supplier) and isinstance(supplier, dict):
         supplier = Supplier.objects.get(pk=supplier['id'])
     
     product = Product(supply=supply, supplier=supplier, cost=cost, upc=upc)
     product.save()
     return product
Exemplo n.º 6
0
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(SupplyAPITestCase, self).setUp()

        self.create_user()
        self.client.login(username="******", password="******")

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supplier2 = Supplier.objects.create(**base_supplier)
        self.supply = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply2.pk)
        self.supply3 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply3.pk)
        self.supply4 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply4.pk)

        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()

        self.employee = Employee(first_name="John", last_name="Smith")
        self.employee.save()
Exemplo n.º 7
0
    def hydrate(self, bundle):
        """
        Prepare the fabric to be saved to the database
        """
        bundle.obj.description = "Pattern:{0}, Col: {1}".format(
            bundle.data['pattern'], bundle.data['color'])
        bundle.obj.type = "Fabric"
        bundle.obj.units = 'm'

        if "cost" in bundle.data:
            if float(bundle.data['cost']) > 0:
                try:
                    try:
                        p = Product.objects.get(
                            supply=bundle.obj,
                            supplier=Supplier.objects.get(
                                pk=bundle.data['supplier']['id']))
                    except Product.DoesNotExist:
                        p = Product()
                        p.supply = bundle.obj
                        p.supplier = Supplier.objects.get(
                            pk=bundle.data['supplier']['id'])
                        p.cost = bundle.data['cost']
                    p.save()
                except KeyError:
                    pass

        return bundle
Exemplo n.º 8
0
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(FabricAPITestCase, self).setUp()

        self.create_user()
        self.client.login(username='******', password='******')

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supply = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)

        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()
Exemplo n.º 9
0
 def obj_create(self, bundle, **kwargs):
     """
     Creates the supply, and then respectively 
     creates the intermediary product instance for the
     many to many relationship with suppliers
     
     We must separate the suppliers data before calling the parent 
     obj_create method
     """
     
     try:
         suppliers = bundle.data['suppliers']
     except KeyError:
         suppliers = [bundle.data['supplier']]
     
     #Initial supply creation
     bundle = super(SupplyResource, self).obj_create(bundle, **kwargs)
     
     #Creates products to establish supplier/supply relationship
     for supplier in suppliers:
         #Gets or creates a new product
         try:
             product = Product(supply=bundle.obj, supplier=Supplier.objects.get(pk=supplier['id']))
         except Product.DoesNotExist as e:
             product = Product(supplier=Supplier.objects.get(pk=supplier['id']),
                               supply=bundle.obj)
         product = self.hydrate_product(product=product, bundle=bundle, **supplier)
         product.save()
     
         log = Log(supply=product.supply,
                   supplier=product.supplier,
                   action="PRICE CHANGE",
                   quantity=None,
                   cost=product.cost,
                   message=u"Price set to {0}{1} for {2} [Supplier: {3}]".format(product.cost,
                                                                                product.supplier.currency,
                                                                                product.supply.description,
                                                                                product.supplier.name))
         log.save()
         
     return bundle
Exemplo n.º 10
0
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(FabricAPITestCase, self).setUp()

        self.create_user()
        self.client.login(username="******", password="******")

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supply = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)

        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()
Exemplo n.º 11
0
    def obj_create(self, bundle, **kwargs):
        """
        Creates the supply, and then respectively 
        creates the intermediary product instance for the
        many to many relationship with suppliers
        
        We must separate the suppliers data before calling the parent 
        obj_create method
        """

        try:
            suppliers = bundle.data['suppliers']
        except KeyError:
            suppliers = [bundle.data['supplier']]

        #Initial supply creation
        bundle = super(SupplyResource, self).obj_create(bundle, **kwargs)

        #Creates products to establish supplier/supply relationship
        for supplier in suppliers:
            #Gets or creates a new product
            try:
                product = Product(
                    supply=bundle.obj,
                    supplier=Supplier.objects.get(pk=supplier['id']))
            except Product.DoesNotExist as e:
                product = Product(
                    supplier=Supplier.objects.get(pk=supplier['id']),
                    supply=bundle.obj)
            product = self.hydrate_product(product=product,
                                           bundle=bundle,
                                           **supplier)
            product.save()

            log = Log(
                supply=product.supply,
                supplier=product.supplier,
                action="PRICE CHANGE",
                quantity=None,
                cost=product.cost,
                message=u"Price set to {0}{1} for {2} [Supplier: {3}]".format(
                    product.cost, product.supplier.currency,
                    product.supply.description, product.supplier.name))
            log.save()

        return bundle
Exemplo n.º 12
0
 def hydrate(self, bundle):
     """
     Prepare the fabric to be saved to the database
     """
     bundle.obj.description = "Pattern:{0}, Col: {1}".format(bundle.data['pattern'], bundle.data['color'])
     bundle.obj.type = "Fabric"
     bundle.obj.units = 'm'
     
     if "cost" in bundle.data:
         if float(bundle.data['cost']) > 0:
             try:
                 try: 
                     p = Product.objects.get(supply=bundle.obj,
                                             supplier=Supplier.objects.get(pk=bundle.data['supplier']['id']))
                 except Product.DoesNotExist:
                     p = Product()
                     p.supply = bundle.obj
                     p.supplier = Supplier.objects.get(pk=bundle.data['supplier']['id'])
                     p.cost = bundle.data['cost']
                 p.save()
             except KeyError:
                 pass
     
     return bundle
Exemplo n.º 13
0
class SupplyAPITest(APITestCase):
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(SupplyAPITest, self).setUp()

        self.create_user()
        self.client.login(username='******', password='******')

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supplier2 = Supplier.objects.create(**base_supplier)
        self.supply = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply2.pk)
        self.supply3 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply3.pk)
        self.supply4 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply4.pk)

        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()

        self.employee = Employee(first_name="John", last_name="Smith")
        self.employee.save()

    def create_user(self):
        self.user = User.objects.create_user('test', '*****@*****.**', 'test')
        self.ct = ContentType(app_label='supplies')
        self.ct.save()
        self._create_and_add_permission('view_cost', self.user)
        self._create_and_add_permission('change_supply', self.user)
        self._create_and_add_permission('add_supply', self.user)
        self._create_and_add_permission('add_quantity', self.user)
        self._create_and_add_permission('subtract_quantity', self.user)

    def _create_and_add_permission(self, codename, user):
        p = Permission(content_type=self.ct, codename=codename)
        p.save()
        user.user_permissions.add(p)

    def test_get_list(self):
        """
        Tests that a standard get call works.
        """

        #Testing standard GET
        resp = self.client.get('/api/v1/supply/')
        self.assertEqual(resp.status_code, 200)

        #Tests the returned data
        resp_obj = resp.data
        self.assertIn('results', resp_obj)
        self.assertEqual(len(resp_obj['results']), 4)

    def test_get(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        resp = self.client.get('/api/v1/supply/1/')
        self.assertEqual(resp.status_code, 200)

        obj = resp.data
        #self.assertEqual(Decimal(obj['cost']), Decimal('100'))
        self.assertIn('description', obj)
        self.assertEqual(obj['description'], 'test')
        self.assertIn('type', obj)
        self.assertEqual(obj['type'], 'wood')

        resp = self.client.get('/api/v1/supply/1/?country=TH')
        self.assertEqual(resp.status_code, 200)
        obj = resp.data
        self.assertEqual(obj['quantity'], 10.8)
        self.assertIn('suppliers', obj)
        self.assertEqual(len(obj['suppliers']), 1)
        supplier = obj['suppliers'][0]

    def stest_get_log(self):
        """
        Tests gettings the log for all the supplies
        """

        resp = self.client.get('/api/v1/supply/log/')
        #self.assertEqual(resp.status_code, 200)
        obj = resp.data
        #self.assertIsInstance(obj, list)

    def test_get_without_price(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        #Delete the view cost permission from the user
        self.user.user_permissions.remove(
            Permission.objects.get(codename='view_cost', content_type=self.ct))

        #tests the response
        resp = self.client.get('/api/v1/supply/1/')
        self.assertEqual(resp.status_code, 200)

        #Tests the data returned
        obj = resp.data
        self.assertNotIn("cost", obj)

    def test_get_types(self):
        """
        Tests getting the different types
        used to describe supplies
        """
        resp = self.client.get('/api/v1/supply/type/')
        #self.assertEqual(resp.status_code, 200)
        type_list = resp.data
        #self.assertIn('wood', type_list)

    def test_post_single_supplier(self):
        """
        Tests posting to the server
        """
        #Test creating an objects.
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.post('/api/v1/supply/',
                                format='json',
                                data=base_supply)
        self.assertEqual(resp.status_code, 201, msg=resp)

        #Tests the dat aturned
        obj = resp.data
        self.assertEqual(obj['id'], 5)
        self.assertEqual(obj['width'], '100.00')
        self.assertEqual(obj['depth'], '200.00')
        self.assertEqual(obj['height'], '300.00')
        self.assertEqual(obj['description'], 'test')
        self.assertEqual(obj['height_units'], 'yd')
        self.assertEqual(obj['width_units'], 'm')
        self.assertEqual(obj['notes'], 'This is awesome')
        self.assertIn('type', obj)
        self.assertEqual(obj['type'], 'wood')
        self.assertIn('suppliers', obj)
        self.assertEqual(len(obj['suppliers']), 1)

        #Test Supplier
        supplier = obj['suppliers'][0]
        self.assertEqual(supplier['reference'], 'A2234')
        self.assertEqual(supplier['cost'], Decimal('100'))

        #TEsts the object created
        supply = Supply.objects.order_by('-id').all()[0]
        supply.supplier = supply.suppliers.all()[0]
        self.assertEqual(supply.id, 5)
        self.assertEqual(supply.width, 100)
        self.assertEqual(supply.depth, 200)
        self.assertEqual(supply.height, 300)
        #self.assertEqual(supply.reference, 'A2234')
        self.assertEqual(supply.description, 'test')
        #self.assertEqual(supply.cost, 100)
        self.assertEqual(supply.height_units, 'yd')
        self.assertEqual(supply.width_units, 'm')
        self.assertEqual(supply.notes, 'This is awesome')
        self.assertIsNotNone(supply.type)
        self.assertEqual(supply.type, 'wood')
        self.assertIsNotNone(supply.suppliers)
        self.assertEqual(supply.suppliers.count(), 1)

    def test_posting_with_custom_type(self):
        """
        Testing creating a new resource via POST 
        that has a custom type
        """
        #Testing returned types pre POST
        resp0 = self.client.get('/api/v1/supply/type/', format='json')
        self.assertEqual(resp0.status_code, 200, msg=resp0)
        type_list = resp0.data
        self.assertNotIn('egg', type_list)
        self.assertIn('wood', type_list)
        self.assertEqual(len(type_list), 1)

        #POST
        modified_supply = base_supply.copy()
        modified_supply['type'] = 'egg'
        resp = self.client.post('/api/v1/supply/',
                                format='json',
                                data=modified_supply)
        self.assertEqual(resp.status_code, 201)

        #Tests the response
        obj = resp.data
        self.assertIn('type', obj)
        self.assertNotIn('custom-type', obj)
        self.assertEqual(obj['type'], 'egg')
        """
        resp2 = self.client.get('/api/v1/supply/type/', format='json')
        self.assertHttpOK(resp2)
        type_list = self.deserialize(resp2)
        self.assertIn('egg', type_list)
        self.assertIn('wood', type_list)
        self.assertEqual(len(type_list), 2)
        """

    def test_put(self):
        """
        Tests adding quantity to the item
        """

        #Validate original data
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.quantity, 10.8)
        self.assertEqual(Log.objects.all().count(), 0)

        #Prepare modified data for PUT
        modified_data = base_supply.copy()
        modified_data['description'] = 'new'
        modified_data['type'] = 'Glue'
        modified_data['quantity'] = '11'

        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.put('/api/v1/supply/1/?country=TH',
                               format='json',
                               data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)

        #Tests the returned data
        obj = resp.data
        self.assertEqual(obj['type'], 'Glue')
        self.assertEqual(float(obj['quantity']), 11)
        self.assertEqual(obj['description'], 'new')
        self.assertFalse(obj.has_key('quantity_th'))
        self.assertFalse(obj.has_key('quantity_kh'))

        #Tests the resource in the database
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.type, 'Glue')
        self.assertEqual(supply.country, 'TH')
        self.assertEqual(supply.description, 'new')
        self.assertEqual(supply.quantity, 11)
        self.assertEqual(Log.objects.all().count(), 1)
        log = Log.objects.all()[0]
        self.assertEqual(log.action, 'ADD')
        self.assertEqual(log.quantity, Decimal('0.2'))
        self.assertEqual(log.message, "Added 0.2ml to new")

    def test_put_without_quantity_change(self):
        """
        Tests adding quantity to the item
        """

        #Validate original data
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.quantity, 10.8)
        self.assertEqual(Log.objects.all().count(), 0)

        #Prepare modified data for PUT
        modified_data = base_supply.copy()
        modified_data['description'] = 'new'
        modified_data['type'] = 'Glue'
        modified_data['quantity'] = '10.8'
        modified_data['width_units'] = 'cm'
        modified_data['depth_units'] = 'cm'

        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.put('/api/v1/supply/1/?country=TH',
                               format='json',
                               data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)

        #Tests the returned data
        obj = resp.data
        self.assertEqual(obj['type'], 'Glue')
        self.assertEqual(float(obj['quantity']), 10.8)
        self.assertEqual(obj['description'], 'new')
        self.assertEqual(obj['width_units'], 'cm')
        self.assertEqual(obj['depth_units'], 'cm')
        self.assertFalse(obj.has_key('quantity_th'))
        self.assertFalse(obj.has_key('quantity_kh'))

        #Tests the resource in the database
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.type, 'Glue')
        self.assertEqual(supply.country, 'TH')
        self.assertEqual(supply.description, 'new')
        self.assertEqual(supply.quantity, 10.8)

        self.assertEqual(Log.objects.all().count(), 0)

    def test_put_subtracting_quantity_to_0(self):
        """
        Tests adding quantity to the item
        """

        #Validate original data
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        supply.quantity = 1
        supply.save()

        self.assertEqual(supply.quantity, 1)
        self.assertEqual(Log.objects.all().count(), 0)

        #Prepare modified data for PUT
        modified_data = base_supply.copy()
        modified_data['description'] = 'new'
        modified_data['type'] = 'Glue'
        modified_data['quantity'] = '0'

        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.put('/api/v1/supply/1/?country=TH',
                               format='json',
                               data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)

        #Tests the returned data
        obj = resp.data
        self.assertEqual(obj['quantity'], 0)

        self.assertFalse(obj.has_key('quantity_th'))
        self.assertFalse(obj.has_key('quantity_kh'))

        #Tests the resource in the database
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.quantity, 0)

        log = Log.objects.all().order_by('-id')[0]
        self.assertEqual(Log.objects.all().count(), 1)
        self.assertEqual(log.quantity, 1)
        self.assertEqual(log.action, 'SUBTRACT')

    @unittest.skip('Not yet implemented')
    def test_add(self):
        """
        Tests adding a quantity
        to the specific url
        """
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.post('/api/v1/supply/1/add/?quantity=5',
                                format='json')
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('15.8'))

    @unittest.skip('Not yet implemented')
    def test_subract(self):
        """
        Tests adding a quantity
        to the specific url
        """
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.post('/api/v1/supply/1/subtract/?quantity=5',
                                format='json')
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('5.8'))

    def test_put_add_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['quantity'] = '14'
        modified_data['description'] = 'new'

        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.put('/api/v1/supply/1/',
                               format='json',
                               data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('14'))
        self.assertEqual(Supply.objects.get(pk=1).description, 'new')

        #Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('14'))

    def test_put_subtract_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['quantity'] = '8'

        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.put('/api/v1/supply/1/',
                               format='json',
                               data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('8'))

        #Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('8'))

    def test_put_to_create_new_product(self):
        """
        Tests adding a new supplier/product to the supply
        """
        logger.debug("\n\nTest creating a new supply/product via PUT\n")
        modified_data = copy.deepcopy(base_supply)
        modified_data['suppliers'] = [{
            'id': 1,
            'supplier': {
                'id': 1
            },
            'reference': 'BOO',
            'cost': '123.45'
        }, {
            'reference': 'A4',
            'cost': '19.99',
            'purchasing_units': 'ml',
            'quantity_per_purchasing_unit': 4,
            'supplier': {
                'id': 2
            }
        }]

        resp = self.client.put('/api/v1/supply/1/',
                               format='json',
                               data=modified_data)

        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 4)

        obj = resp.data
        self.assertIn('suppliers', obj)
        self.assertEqual(len(obj['suppliers']), 2)
        supplier1 = obj['suppliers'][0]
        self.assertEqual(supplier1['reference'], 'BOO')
        self.assertEqual(supplier1['cost'], Decimal('123.45'))

        supplier2 = obj['suppliers'][1]
        self.assertEqual(supplier2['reference'], 'A4')
        self.assertEqual(supplier2['cost'], Decimal('19.99'))
        self.assertEqual(supplier2['purchasing_units'], 'ml')
        self.assertEqual(supplier2['quantity_per_purchasing_unit'],
                         Decimal('4'))
        self.assertEqual(supplier2['supplier']['id'], 2)

    def test_updating_multiple_supplies(self):
        """
        Test that we can update the quantities of multiple supplies
        """
        data = [{
            'id': 1,
            'description': 'poooo',
            'quantity': 9,
            'employee': {
                'id': 1
            }
        }, {
            'id': 2,
            'quantity': 12.3,
            'employee': {
                'id': 1
            }
        }]

        resp = self.client.put('/api/v1/supply/', format='json', data=data)
        self.assertEqual(resp.status_code, 200, msg=resp)
        supplies = resp.data

        supply1 = supplies[0]
        self.assertEqual(supply1['quantity'], 9)
        self.assertEqual(supply1['description'], u'poooo')
        supply1_obj = Supply.objects.get(pk=1)
        self.assertEqual(supply1_obj.quantity, 9)

        supply2 = supplies[1]
        self.assertEqual(supply2['quantity'], Decimal('12.3'))
        supply2_obj = Supply.objects.get(pk=2)
        self.assertEqual(supply2_obj.quantity, 12.3)

        log1 = Log.objects.all()[0]
        self.assertEqual(log1.action, "SUBTRACT")
        self.assertEqual(log1.quantity, Decimal('1.8'))
        self.assertIsNotNone(log1.employee)
        self.assertEqual(log1.employee.id, 1)
        self.assertEqual(log1.employee.first_name, "John")
        self.assertEqual(log1.employee.last_name, "Smith")

        log2 = Log.objects.all()[1]
        self.assertEqual(log2.action, "ADD")
        self.assertEqual(log2.quantity, Decimal('1.5'))
        self.assertIsNotNone(log2.employee)
        self.assertEqual(log2.employee.id, 1)
        self.assertEqual(log2.employee.first_name, "John")
        self.assertEqual(log2.employee.last_name, "Smith")

    def test_bulk_update_with_new_supply(self):
        """
        Test that we can update the quantities of multiple supplies
        """
        data = [{
            'id': 1,
            'description': 'poooo',
            'quantity': 9,
            'employee': {
                'id': 1
            }
        }, {
            'id': 2,
            'quantity': 12.3,
            'employee': {
                'id': 1
            }
        }, {
            'description': 'slat wood',
            'quantity': 10
        }]

        resp = self.client.put('/api/v1/supply/', format='json', data=data)
        self.assertEqual(resp.status_code, 200, msg=resp)
        supplies = resp.data

        supply1 = supplies[0]
        self.assertEqual(supply1['quantity'], 9)
        self.assertEqual(supply1['description'], u'poooo')
        supply1_obj = Supply.objects.get(pk=1)
        self.assertEqual(supply1_obj.quantity, 9)

        supply2 = supplies[1]
        self.assertEqual(supply2['quantity'], Decimal('12.3'))
        supply2_obj = Supply.objects.get(pk=2)
        self.assertEqual(supply2_obj.quantity, 12.3)

        supply3 = supplies[2]
        logger.debug(supply3)
        self.assertEqual(supply3['description'], 'slat wood')
        self.assertEqual(supply3['quantity'], Decimal('10'))
        supply3_obj = Supply.objects.get(pk=supply3['id'])
        self.assertEqual(supply3_obj.description, 'slat wood')
        self.assertEqual(supply3_obj.quantity, 10)

        log1 = Log.objects.all()[0]
        self.assertEqual(log1.action, "SUBTRACT")
        self.assertEqual(log1.quantity, Decimal('1.8'))
        self.assertIsNotNone(log1.employee)
        self.assertEqual(log1.employee.id, 1)
        self.assertEqual(log1.employee.first_name, "John")
        self.assertEqual(log1.employee.last_name, "Smith")

        log2 = Log.objects.all()[1]
        self.assertEqual(log2.action, "ADD")
        self.assertEqual(log2.quantity, Decimal('1.5'))
        self.assertIsNotNone(log2.employee)
        self.assertEqual(log2.employee.id, 1)
        self.assertEqual(log2.employee.first_name, "John")
        self.assertEqual(log2.employee.last_name, "Smith")
Exemplo n.º 14
0
def work():
    data = []
    review = []
    supplier = Supplier.objects.get(name__icontains="blue international")
    with open("/Users/Charlie/Sites/employee/backend/blue-inter.csv", 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            data.append({'reference': row[0],
                         'description': row[1],
                         'cost': row[2],
                         'units': row[3]})
                             
    for index, d in enumerate(data):
        for key in d.keys():
                try:
                    d[key] = d[key].encode('utf-8')
                except UnicodeDecodeError as e:
                    pass
                    
                if key == "cost":
                    try:
                        d[key] = Decimal(d[key].replace(',', ''))
                    except InvalidOperation as e:
                        review.append(data.pop(index))
                        
                if key == "units":
                    if not d[key]:
                        review.append(data.pop(index))

    for index, d in enumerate(data):
        try:
            try:
                supply = Supply.objects.get(description=d['description'])
            except Supply.DoesNotExist:
                supply = Supply()
        
            supply.description = d['description']
            supply.units = d['units']
            supply.full_clean()
            supply.save()
        
        
            try:
                product = Product.objects.get(supply=supply)
            except Product.DoesNotExist:
                product = Product(supply=supply, supplier=supplier)
            
            product.supplier = supplier
            product.supply = supply
            product.reference = d['reference']
            product.cost = d['cost']
            product.purchasing_units = d['units']
            product.full_clean()
            product.save()
            
        except ValidationError as e:
            print e
            review.append(data.pop(index))
            
        assert Supply.objects.filter(description=d['description']).count() == 1
        
    with open('blue-inter-review.csv', 'w') as f:
        fieldnames = ['reference', 'description', 'cost', 'units']
        writer = csv.DictWriter(f)
        writer.write_header()
        for d in review:
            writer.writerow(d)
        
    assert supplier.supplies.all().count() == len(data)
Exemplo n.º 15
0
class FabricAPITestCase(APITestCase):
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(FabricAPITestCase, self).setUp()

        self.create_user()
        self.client.login(username='******', password='******')

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supply = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)

        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()

    def create_user(self):
        self.user = User.objects.create_user('test', '*****@*****.**', 'test')
        self.ct = ContentType(app_label='supplies')
        self.ct.save()
        self._create_and_add_permission('view_cost', self.user)
        self._create_and_add_permission('change_fabric', self.user)
        self._create_and_add_permission('add_fabric', self.user)
        self._create_and_add_permission('add_quantity', self.user)
        self._create_and_add_permission('subtract_quantity', self.user)

    def _create_and_add_permission(self, codename, user):
        p = Permission(content_type=self.ct, codename=codename)
        p.save()
        user.user_permissions.add(p)

    def _remove_permission(self, codename):
        self.user.user_permissions.remove(
            Permission.objects.get(codename=codename, content_type=self.ct))

    def test_get_list(self):
        """
        Tests that a standard get call works.
        """

        #Testing standard GET
        resp = self.client.get('/api/v1/fabric/')
        self.assertEqual(resp.status_code, 200)

        #Tests the returned data
        resp_obj = resp.data
        self.assertIn('results', resp_obj)
        self.assertEqual(len(resp_obj['results']), 2)

    def test_get(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        resp = self.client.get('/api/v1/fabric/1/')
        self.assertEqual(resp.status_code, 200)

        obj = resp.data
        #self.assertEqual(float(obj['cost']), float('100'))

    def test_get_without_price(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        #Delete the view cost permission from the user
        self.user.user_permissions.remove(
            Permission.objects.get(codename='view_cost', content_type=self.ct))

        #tests the response
        resp = self.client.get('/api/v1/fabric/1/')
        self.assertEqual(resp.status_code, 200)

        #Tests the data returned
        obj = resp.data
        self.assertNotIn("cost", obj)

    def test_post(self):
        """
        Tests posting to the server
        """
        #Test creating an objects.
        self.assertEqual(Supply.objects.count(), 2)
        resp = self.client.post('/api/v1/fabric/',
                                format='json',
                                data=base_fabric)
        self.assertEqual(resp.status_code, 201, msg=resp)

        #Tests the dat aturned
        obj = resp.data
        self.assertEqual(obj['id'], 3)
        self.assertEqual(obj['width'], '100.00')
        self.assertEqual(obj['depth'], '0.00')
        self.assertEqual(obj['height'], '300.00')
        self.assertEqual(obj['description'], u'Max Col: Hot Pink')
        self.assertNotIn('reference', obj)
        self.assertNotIn('cost', obj)
        self.assertIn('suppliers', obj)

        supplier = obj['suppliers'][0]
        self.assertEqual(supplier['reference'], 'A2234')
        self.assertEqual(int(supplier['cost']), 100)

    def test_put(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['cost'] = '111'
        modified_data['color'] = 'Aqua'
        modified_data['pattern'] = 'Stripes'
        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 2)
        resp = self.client.put('/api/v1/fabric/1/',
                               format='json',
                               data=modified_data)

        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 2)

        #Tests the returned data
        obj = resp.data
        self.assertEqual(obj['color'], 'Aqua')
        self.assertEqual(obj['pattern'], 'Stripes')

    def test_put_add_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['quantity'] = '14'
        modified_data['color'] = 'Aqua'
        modified_data['pattern'] = 'Stripes'

        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.put('/api/v1/fabric/1/',
                               format='json',
                               data=modified_data)
        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('14'))

        #Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('14'))

    def test_put_subtract_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['quantity'] = '8'
        modified_data['color'] = 'Aqua'
        modified_data['pattern'] = 'Stripes'

        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.put('/api/v1/fabric/1/',
                               format='json',
                               data=modified_data)

        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('8'))

        #Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('8'))

    @unittest.skip('ok')
    def test_put_add_quantity_fail(self):
        """
        Tests an unauthorized addition of quantity
        """
        #Delete permissions
        self._remove_permission("add_quantity")

        #Create new data
        modified_data = base_fabric.copy()
        modified_data['quantity'] = '20'

        #Tests the api and response
        resp = self.client.put('/api/v1/fabric/1/',
                               format='json',
                               data=modified_data)
        self.assertEqual(Fabric.objects.get(pk=1).quantity, float('10.8'))
        #Tests the data retured
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('10.8'))

    @unittest.skip('ok')
    def test_put_subtract_quantity_fail(self):
        """
        Tests an unauthorized addition of quantity
        """
        #Delete permissions
        self._remove_permission("subtract_quantity")

        #Create new data
        modified_data = base_fabric.copy()
        modified_data['quantity'] = '6'

        #Tests the api and response
        resp = self.client.put('/api/v1/fabric/1/',
                               format='json',
                               data=modified_data)
        self.assertEqual(Fabric.objects.get(pk=1).quantity, float('10.8'))
        #Tests the data retured
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('10.8'))
Exemplo n.º 16
0
        fabric.grade = f['grade']
        fabric.repeat = f['repeat']
        fabric.units = 'yd'
        fabric.type = 'fabric'
        fabric.save()

        filename = "{0} Col: {1}".format(fabric.pattern, fabric.color)
        fabric.description = filename
        fabric.save()

        print fabric.id, fabric.description

        try:
            product = Product.objects.get(supply=fabric, supplier=supplier)
        except Product.DoesNotExist:
            product = Product(supply=fabric, supplier=supplier)

        product.purchasing_units = 'yd'
        try:
            product.cost = Decimal(fabric.grade) * Decimal('1.10')
        except Exception:
            product.cost = 0

        product.save()

        if 'image' in f:
            f['image'].save(filename + ".jpg")
            image = S3Object.create(
                filename + ".jpg",
                "supply/image/{0}-{1}.jpg".format(fabric.pattern,
                                                  fabric.color),
Exemplo n.º 17
0
class SupplyAPITest(APITestCase):
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(SupplyAPITest, self).setUp()
        
        self.create_user()
        self.client.login(username='******', password='******')
        
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supplier2 = Supplier.objects.create(**base_supplier)
        self.supply = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply2.pk)
        self.supply3 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply3.pk)
        self.supply4 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply4.pk)
        
        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()
        
        self.employee = Employee(first_name="John", last_name="Smith")
        self.employee.save()
        
    def create_user(self):
        self.user = User.objects.create_user('test', '*****@*****.**', 'test')
        self.ct = ContentType(app_label='supplies')
        self.ct.save()
        self._create_and_add_permission('view_cost', self.user)
        self._create_and_add_permission('change_supply', self.user)
        self._create_and_add_permission('add_supply', self.user)
        self._create_and_add_permission('add_quantity', self.user)
        self._create_and_add_permission('subtract_quantity', self.user)
       
        
    def _create_and_add_permission(self, codename, user):
        p = Permission(content_type=self.ct, codename=codename)
        p.save()
        user.user_permissions.add(p)
        
    def test_get_list(self):
        """
        Tests that a standard get call works.
        """
        
        #Testing standard GET
        resp = self.client.get('/api/v1/supply/')
        self.assertEqual(resp.status_code, 200)
        
        #Tests the returned data
        resp_obj = resp.data
        self.assertIn('results', resp_obj)
        self.assertEqual(len(resp_obj['results']), 4)
    
    def test_get(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        resp = self.client.get('/api/v1/supply/1/')
        self.assertEqual(resp.status_code, 200)
        
        obj = resp.data
        #self.assertEqual(Decimal(obj['cost']), Decimal('100'))
        self.assertIn('description', obj)
        self.assertEqual(obj['description'], 'test')
        self.assertIn('type', obj)
        self.assertEqual(obj['type'], 'wood')
        

        resp = self.client.get('/api/v1/supply/1/?country=TH')
        self.assertEqual(resp.status_code, 200)
        obj = resp.data
        self.assertEqual(obj['quantity'], 10.8)
        self.assertIn('suppliers', obj)
        self.assertEqual(len(obj['suppliers']), 1)
        supplier = obj['suppliers'][0]
    
    def stest_get_log(self):
        """
        Tests gettings the log for all the supplies
        """
        
        resp = self.client.get('/api/v1/supply/log/')
        #self.assertEqual(resp.status_code, 200)
        obj = resp.data
        #self.assertIsInstance(obj, list)
    
    def test_get_without_price(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        #Delete the view cost permission from the user
        self.user.user_permissions.remove(Permission.objects.get(codename='view_cost', content_type=self.ct))
        
        #tests the response
        resp = self.client.get('/api/v1/supply/1/')
        self.assertEqual(resp.status_code, 200)
        
        #Tests the data returned
        obj = resp.data
        self.assertNotIn("cost", obj)
    
    def test_get_types(self):
        """
        Tests getting the different types
        used to describe supplies
        """
        resp = self.client.get('/api/v1/supply/type/')
        #self.assertEqual(resp.status_code, 200)
        type_list = resp.data
        #self.assertIn('wood', type_list)
        
    def test_post_single_supplier(self):
        """
        Tests posting to the server
        """
        #Test creating an objects. 
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.post('/api/v1/supply/', format='json',
                                    data=base_supply)
        self.assertEqual(resp.status_code, 201, msg=resp)

        #Tests the dat aturned
        obj = resp.data
        self.assertEqual(obj['id'], 5)
        self.assertEqual(obj['width'], '100.00')
        self.assertEqual(obj['depth'], '200.00')
        self.assertEqual(obj['height'], '300.00')
        self.assertEqual(obj['description'], 'test')
        self.assertEqual(obj['height_units'], 'yd')
        self.assertEqual(obj['width_units'], 'm')
        self.assertEqual(obj['notes'], 'This is awesome')
        self.assertIn('type', obj)
        self.assertEqual(obj['type'], 'wood')
        self.assertIn('suppliers', obj)
        self.assertEqual(len(obj['suppliers']), 1)
        
        #Test Supplier
        supplier = obj['suppliers'][0]
        self.assertEqual(supplier['reference'], 'A2234')
        self.assertEqual(supplier['cost'], Decimal('100'))
        
        #TEsts the object created
        supply = Supply.objects.order_by('-id').all()[0]
        supply.supplier = supply.suppliers.all()[0]
        self.assertEqual(supply.id, 5)
        self.assertEqual(supply.width, 100)
        self.assertEqual(supply.depth, 200)
        self.assertEqual(supply.height, 300)
        #self.assertEqual(supply.reference, 'A2234')
        self.assertEqual(supply.description, 'test')
        #self.assertEqual(supply.cost, 100)
        self.assertEqual(supply.height_units, 'yd')
        self.assertEqual(supply.width_units, 'm')
        self.assertEqual(supply.notes, 'This is awesome')
        self.assertIsNotNone(supply.type)
        self.assertEqual(supply.type, 'wood')
        self.assertIsNotNone(supply.suppliers)
        self.assertEqual(supply.suppliers.count(), 1)

    def test_posting_with_custom_type(self):
        """
        Testing creating a new resource via POST 
        that has a custom type
        """
        #Testing returned types pre POST
        resp0 = self.client.get('/api/v1/supply/type/', format='json')
        self.assertEqual(resp0.status_code, 200, msg=resp0)
        type_list = resp0.data
        self.assertNotIn('egg', type_list)
        self.assertIn('wood', type_list)
        self.assertEqual(len(type_list), 1)
        
        #POST
        modified_supply = base_supply.copy()
        modified_supply['type'] = 'egg'
        resp = self.client.post('/api/v1/supply/', format='json',
                                    data=modified_supply)
        self.assertEqual(resp.status_code, 201)
        
        #Tests the response
        obj = resp.data
        self.assertIn('type', obj)
        self.assertNotIn('custom-type', obj)
        self.assertEqual(obj['type'], 'egg')
        
        """
        resp2 = self.client.get('/api/v1/supply/type/', format='json')
        self.assertHttpOK(resp2)
        type_list = self.deserialize(resp2)
        self.assertIn('egg', type_list)
        self.assertIn('wood', type_list)
        self.assertEqual(len(type_list), 2)
        """
        
    def test_put(self):
        """
        Tests adding quantity to the item
        """
        
        #Validate original data
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.quantity, 10.8)
        self.assertEqual(Log.objects.all().count(), 0)
        
        #Prepare modified data for PUT
        modified_data = base_supply.copy()
        modified_data['description'] = 'new'
        modified_data['type'] = 'Glue'
        modified_data['quantity'] = '11'
        
        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.put('/api/v1/supply/1/?country=TH', format='json',
                                   data=modified_data)
        
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)

        #Tests the returned data
        obj = resp.data
        self.assertEqual(obj['type'], 'Glue')
        self.assertEqual(float(obj['quantity']), 11)
        self.assertEqual(obj['description'], 'new')
        self.assertFalse(obj.has_key('quantity_th'))
        self.assertFalse(obj.has_key('quantity_kh'))
        
        #Tests the resource in the database
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.type, 'Glue')
        self.assertEqual(supply.country, 'TH')
        self.assertEqual(supply.description, 'new')
        self.assertEqual(supply.quantity, 11)
        self.assertEqual(Log.objects.all().count(), 1)
        log = Log.objects.all()[0]
        self.assertEqual(log.action, 'ADD')
        self.assertEqual(log.quantity, Decimal('0.2'))
        self.assertEqual(log.message, "Added 0.2ml to new")
        
    def test_put_without_quantity_change(self):
        """
        Tests adding quantity to the item
        """
        
        #Validate original data
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.quantity, 10.8)
        self.assertEqual(Log.objects.all().count(), 0)
        
        #Prepare modified data for PUT
        modified_data = base_supply.copy()
        modified_data['description'] = 'new'
        modified_data['type'] = 'Glue'
        modified_data['quantity'] = '10.8'
        modified_data['width_units'] = 'cm'
        modified_data['depth_units'] = 'cm'
        
        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.put('/api/v1/supply/1/?country=TH', format='json',
                                   data=modified_data)
        
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)

        #Tests the returned data
        obj = resp.data
        self.assertEqual(obj['type'], 'Glue')
        self.assertEqual(float(obj['quantity']), 10.8)
        self.assertEqual(obj['description'], 'new')
        self.assertEqual(obj['width_units'], 'cm')
        self.assertEqual(obj['depth_units'], 'cm')
        self.assertFalse(obj.has_key('quantity_th'))
        self.assertFalse(obj.has_key('quantity_kh'))
        
        #Tests the resource in the database
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.type, 'Glue')
        self.assertEqual(supply.country, 'TH')
        self.assertEqual(supply.description, 'new')
        self.assertEqual(supply.quantity, 10.8)
        
        self.assertEqual(Log.objects.all().count(), 0)
        
    def test_put_subtracting_quantity_to_0(self):
        """
        Tests adding quantity to the item
        """
        
        #Validate original data
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        supply.quantity = 1
        supply.save()
        
        self.assertEqual(supply.quantity, 1)
        self.assertEqual(Log.objects.all().count(), 0)
        
        #Prepare modified data for PUT
        modified_data = base_supply.copy()
        modified_data['description'] = 'new'
        modified_data['type'] = 'Glue'
        modified_data['quantity'] = '0'
        
        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.put('/api/v1/supply/1/?country=TH', format='json',
                                   data=modified_data)
        
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)

        #Tests the returned data
        obj = resp.data
        self.assertEqual(obj['quantity'], 0)

        self.assertFalse(obj.has_key('quantity_th'))
        self.assertFalse(obj.has_key('quantity_kh'))
        
        #Tests the resource in the database
        supply = Supply.objects.get(pk=1)
        supply.country = 'TH'
        self.assertEqual(supply.quantity, 0)
        
        log = Log.objects.all().order_by('-id')[0]
        self.assertEqual(Log.objects.all().count(), 1)
        self.assertEqual(log.quantity, 1)
        self.assertEqual(log.action, 'SUBTRACT')
        
    @unittest.skip('Not yet implemented')    
    def test_add(self):
        """
        Tests adding a quantity
        to the specific url
        """
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.post('/api/v1/supply/1/add/?quantity=5', format='json')
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('15.8'))
        
    @unittest.skip('Not yet implemented')    
    def test_subract(self):
        """
        Tests adding a quantity
        to the specific url
        """
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.post('/api/v1/supply/1/subtract/?quantity=5', format='json')
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('5.8'))
        
    def test_put_add_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['quantity'] = '14'
        modified_data['description'] = 'new'
        
        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.put('/api/v1/supply/1/', format='json',
                                   data=modified_data)
        
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('14'))
        self.assertEqual(Supply.objects.get(pk=1).description, 'new')

        #Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('14'))
    
    def test_put_subtract_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['quantity'] = '8'
        
        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.put('/api/v1/supply/1/', format='json',
                                   data=modified_data)
        
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('8'))

        #Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('8'))
        
    def test_put_to_create_new_product(self):
        """
        Tests adding a new supplier/product to the supply
        """
        logger.debug("\n\nTest creating a new supply/product via PUT\n")
        modified_data = copy.deepcopy(base_supply)
        modified_data['suppliers'] = [{'id': 1,
                                       'supplier': {'id': 1},
                                       'reference': 'BOO', 
                                       'cost': '123.45'},
                                      {'reference': 'A4',
                                        'cost': '19.99',
                                        'purchasing_units': 'ml',
                                        'quantity_per_purchasing_unit': 4,
                                        'supplier': {'id': 2}}]
                                        
        resp = self.client.put('/api/v1/supply/1/', format='json', data=modified_data)
        
        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 4)
        
        obj = resp.data
        self.assertIn('suppliers', obj)
        self.assertEqual(len(obj['suppliers']), 2)
        supplier1 = obj['suppliers'][0]
        self.assertEqual(supplier1['reference'], 'BOO')
        self.assertEqual(supplier1['cost'], Decimal('123.45'))
        
        supplier2 = obj['suppliers'][1]
        self.assertEqual(supplier2['reference'], 'A4')
        self.assertEqual(supplier2['cost'], Decimal('19.99'))
        self.assertEqual(supplier2['purchasing_units'], 'ml')
        self.assertEqual(supplier2['quantity_per_purchasing_unit'], Decimal('4'))
        self.assertEqual(supplier2['supplier']['id'], 2)
        
    def test_updating_multiple_supplies(self):
        """
        Test that we can update the quantities of multiple supplies
        """
        data = [{'id': 1, 'description': 'poooo', 'quantity': 9, 'employee': {'id': 1}}, {'id':2, 'quantity': 12.3, 'employee': {'id': 1}}]
        
        resp = self.client.put('/api/v1/supply/', format='json', data=data)
        self.assertEqual(resp.status_code, 200, msg=resp)
        supplies = resp.data

        supply1 = supplies[0]
        self.assertEqual(supply1['quantity'], 9)
        self.assertEqual(supply1['description'], u'poooo')
        supply1_obj = Supply.objects.get(pk=1)
        self.assertEqual(supply1_obj.quantity, 9)
        
        supply2 = supplies[1]
        self.assertEqual(supply2['quantity'], Decimal('12.3'))
        supply2_obj = Supply.objects.get(pk=2)
        self.assertEqual(supply2_obj.quantity, 12.3)
                
        log1 = Log.objects.all()[0]
        self.assertEqual(log1.action, "SUBTRACT")
        self.assertEqual(log1.quantity, Decimal('1.8'))
        self.assertIsNotNone(log1.employee)
        self.assertEqual(log1.employee.id, 1)
        self.assertEqual(log1.employee.first_name, "John")
        self.assertEqual(log1.employee.last_name, "Smith")
        
        log2 = Log.objects.all()[1]
        self.assertEqual(log2.action, "ADD")
        self.assertEqual(log2.quantity, Decimal('1.5'))
        self.assertIsNotNone(log2.employee)
        self.assertEqual(log2.employee.id, 1)
        self.assertEqual(log2.employee.first_name, "John")
        self.assertEqual(log2.employee.last_name, "Smith")

    def test_bulk_update_with_new_supply(self):
        """
        Test that we can update the quantities of multiple supplies
        """
        data = [{'id': 1, 'description': 'poooo', 'quantity': 9, 'employee': {'id': 1}}, 
                {'id':2, 'quantity': 12.3, 'employee': {'id': 1}},
                {'description': 'slat wood',
                 'quantity': 10}]
        
        resp = self.client.put('/api/v1/supply/', format='json', data=data)
        self.assertEqual(resp.status_code, 200, msg=resp)
        supplies = resp.data

        supply1 = supplies[0]
        self.assertEqual(supply1['quantity'], 9)
        self.assertEqual(supply1['description'], u'poooo')
        supply1_obj = Supply.objects.get(pk=1)
        self.assertEqual(supply1_obj.quantity, 9)
        
        supply2 = supplies[1]
        self.assertEqual(supply2['quantity'], Decimal('12.3'))
        supply2_obj = Supply.objects.get(pk=2)
        self.assertEqual(supply2_obj.quantity, 12.3)

        supply3 = supplies[2]
        logger.debug(supply3)
        self.assertEqual(supply3['description'], 'slat wood')
        self.assertEqual(supply3['quantity'], Decimal('10'))
        supply3_obj = Supply.objects.get(pk=supply3['id'])
        self.assertEqual(supply3_obj.description, 'slat wood')
        self.assertEqual(supply3_obj.quantity, 10)
                
        log1 = Log.objects.all()[0]
        self.assertEqual(log1.action, "SUBTRACT")
        self.assertEqual(log1.quantity, Decimal('1.8'))
        self.assertIsNotNone(log1.employee)
        self.assertEqual(log1.employee.id, 1)
        self.assertEqual(log1.employee.first_name, "John")
        self.assertEqual(log1.employee.last_name, "Smith")
        
        log2 = Log.objects.all()[1]
        self.assertEqual(log2.action, "ADD")
        self.assertEqual(log2.quantity, Decimal('1.5'))
        self.assertIsNotNone(log2.employee)
        self.assertEqual(log2.employee.id, 1)
        self.assertEqual(log2.employee.first_name, "John")
        self.assertEqual(log2.employee.last_name, "Smith")
Exemplo n.º 18
0
class PurchaseOrderTest(APITestCase):
    """
    Tests the Purchase Order
    """
    def setUp(self):
        """
        Set up dependent objects
        """
        super(PurchaseOrderTest, self).setUp()
        
        self.ct = ContentType(app_label="po")
        self.ct.save()
        self.p = Permission(codename="add_purchaseorder", content_type=self.ct)
        self.p.save()
        self.p2 = Permission(codename="change_purchaseorder", content_type=self.ct)
        self.p2.save()
        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, '*****@*****.**', self.password)
        self.user.save()
        self.user.user_permissions.add(self.p)
        self.user.user_permissions.add(self.p2)
        self.client.login(username=self.username, password=self.password)
        
        
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(**base_address)
        self.address.contact = self.supplier
        self.address.save()
        self.contact = SupplierContact(name='test', email='*****@*****.**', telephone=1234, primary=True)
        self.contact.supplier = self.supplier
        self.contact.save()
        self.supply = Fabric.create(**base_fabric)
       
        #self.supply.units = "m^2"
        self.supply.save()
        self.supply1 = self.supply
        
        self.product = Product(supply=self.supply, supplier=self.supplier, cost=base_fabric['unit_cost'],
                               purchasing_units='m')
        self.product.save()
        self.supply2 = Fabric.create(**base_fabric2)
        self.supply2.discount = 5
        self.supply2.save()
        self.product2 = Product(supply=self.supply2, supplier=self.supplier, cost=base_fabric['unit_cost'])
        self.product2.save()
        self.supply.supplier = self.supplier
        self.supply2.supplier = self.supplier
        
        #Create a project
        self.project = Project()
        self.project.codename = 'MC House'
        self.project.save()
        
        self.po = PurchaseOrder()
        self.po.employee = self.user
        self.po.supplier = self.supplier
        self.po.terms = self.supplier.terms
        self.po.vat = 7
        self.po.order_date = datetime.datetime(2014, 3, 2)
        self.po.save()
        #self.po.create_and_upload_pdf()
        
        self.item = Item.create(supplier=self.supplier, id=1, **base_purchase_order['items'][0])
        self.item.purchase_order = self.po
        self.item.save()
        
        self.po.calculate_total()
        self.po.save()
    
    def test_get_list(self):
        """
        Tests getting a list of po's via GET
        """
        #Validate the response
        resp = self.client.get('/api/v1/purchase-order/', format='json')
        self.assertEqual(resp.status_code, 200)
        
        #Validate the returned data
        resp = resp.data
        self.assertIsInstance(resp, dict)
        self.assertIsInstance(resp['results'], list)
        self.assertEqual(len(resp['results']), 1)
    
    def test_get(self):
        """
        Tests getting a single resource via GET
        """
        #Validate the response
        resp = self.client.get('/api/v1/purchase-order/1/')
        self.assertEqual(resp.status_code, 200)
        
        #Validate the returned data
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertEqual(obj['terms'], 30)
        self.assertEqual(obj['revision'], 0)
        
        #Test items
        self.assertIn('items', obj)
        self.assertEqual(len(obj['items']), 1)
        item1 = obj['items'][0]
        #self.assertIn('purchasing_units', item1)
        #self.assertEqual(item1['purchasing_units'], 'm')
    
    def test_get_with_pdf(self):
        """
        Tests getting a resource with the pdf
        """
        self.skipTest("")
        self.po.create_and_upload_pdf()
        
        resp = self.client.get('/api/v1/purchase-order/1/')
        self.assertEqual(resp.status_code, 200)
        
        obj = resp.data
        self.assertIn('pdf', obj)
        self.assertIn('url', obj['pdf'])
        self.assertIsNotNone(obj['pdf']['url'])

    def test_post(self):
        """
        Tests creating a new resource via POST
        """

        print '\n'
        logger.debug("Creating new po")
        print '\n'
        
        #validate the response
        resp = self.client.post('/api/v1/purchase-order/',
                                data=base_purchase_order, 
                                format='json')
        self.assertEqual(resp.status_code, 201, msg=resp)
        
        #Validate the data returned
        obj = resp.data
        self.assertEqual(obj['id'], 2)
        self.assertIsNotNone(obj['items'])
        self.assertIsInstance(obj['items'], list)
        self.assertEqual(len(obj['items']), 2)
        self.assertEqual(obj['currency'], 'USD')
        self.assertIn('project', obj)
        self.assertIsInstance(obj['project'], dict)
        self.assertEqual(obj['project']['id'], 1)
        self.assertEqual(obj['project']['codename'], 'MC House')

        #validate the resource in the database
        po = PurchaseOrder.objects.get(pk=2)
        self.assertIsInstance(po.project, Project)
        #self.assertIsNotNone(obj['pdf'])
        #self.assertIsNotNone(obj['pdf']['url'])
        self.items = po.items.all().order_by('id')
        self.item1 = self.items[0]
        self.item2 = self.items[1]
        self.assertIsInstance(self.item1, Item)
        self.assertIsInstance(self.item1.supply, Supply)
        self.assertEqual(self.item1.supply.id, 1)
        self.assertEqual(self.item1.unit_cost, Decimal('12.11'))
        self.assertEqual(self.item1.quantity, 10)
        self.assertEqual(self.item1.total, Decimal('121.1'))
        self.assertIsInstance(self.item2, Item)
        self.assertIsInstance(self.item2.supply, Supply)
        self.assertEqual(self.item2.supply.id, 2)
        self.assertEqual(self.item2.unit_cost, Decimal('12.11'))
        self.assertEqual(self.item2.quantity, 3)
        self.assertEqual(self.item2.total, Decimal('34.51'))
        
        self.assertEqual(Project.objects.count(), 1)
        project = Project.objects.all()[0]
        self.assertIsInstance(project, Project)
        self.assertEqual(project.id, 1)
        self.assertEqual(project.codename, 'MC House')
    
    def test_post_with_new_project(self):
        """
        Tests creating a new resource via POST
        """
        print '\n'
        logger.debug("Creating new po with a project")
        print '\n'
        
        #validate the response
        po = base_purchase_order.copy()
        po['project'] = {'codename': 'Ladawan'}
        po['currency'] = 'RMB'
        resp = self.client.post('/api/v1/purchase-order/',
                                data=po,
                                format='json')
        self.assertEqual(resp.status_code, 201, msg=resp)
        
        #Validate the data returned
        obj = resp.data
        self.assertEqual(obj['id'], 2)
        self.assertIsNotNone(obj['items'])
        self.assertIsInstance(obj['items'], list)
        self.assertEqual(len(obj['items']), 2)
        self.assertIn('project', obj)
        self.assertIsInstance(obj['project'], dict)
        self.assertEqual(obj['project']['id'], 2)
        self.assertEqual(obj['project']['codename'], 'Ladawan')
        self.assertEqual(obj['currency'], 'RMB')
        
        #validate the resource in the database
        po = PurchaseOrder.objects.get(pk=2)
        self.assertIsInstance(po.project, Project)
        #self.assertIsNotNone(obj['pdf'])
        #self.assertIsNotNone(obj['pdf']['url'])
        self.items = po.items.all().order_by('id')
        self.item1 = self.items[0]
        self.item2 = self.items[1]
        self.assertIsInstance(self.item1, Item)
        self.assertIsInstance(self.item1.supply, Supply)
        self.assertEqual(self.item1.supply.id, 1)
        self.assertEqual(self.item1.unit_cost, Decimal('12.11'))
        self.assertEqual(self.item1.quantity, 10)
        self.assertEqual(self.item1.total, Decimal('121.1'))
        self.assertIsInstance(self.item2, Item)
        self.assertIsInstance(self.item2.supply, Supply)
        self.assertEqual(self.item2.supply.id, 2)
        #self.assertEqual(self.item2.unit_cost, Decimal('11.50'))
        self.assertEqual(self.item2.quantity, 3)
        self.assertEqual(self.item2.total, Decimal('34.51'))
        
        project = po.project
        self.assertEqual(Project.objects.all().count(), 2)
        self.assertIsInstance(project, Project)
        self.assertEqual(project.id, 2)
        self.assertEqual(project.codename, 'Ladawan')
    
    def test_creating_new_po_with_price_change(self):
        """
        Tests creating a new po via post while also changing the price of a supply
        """
        print '\n'
        logger.debug("Creating new po with a price change")
        print '\n'
        #validate the response
        po = copy.deepcopy(base_purchase_order)
        del po['items'][1]
        po['items'][0]['cost'] = '1.99'
        resp = self.client.post('/api/v1/purchase-order/',
                                data=po,
                                format='json')
        self.assertEqual(resp.status_code, 201, msg=resp)
        resp_obj = resp.data
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(resp_obj['pdf']['url'])
        
        #Verify the returned data
        self.assertEqual(resp_obj['id'], 2)
        self.assertEqual(resp_obj['vat'], 7)
        self.assertEqual(Decimal(resp_obj['grand_total']), Decimal('21.30'))
        item = resp_obj['items'][0]
        self.assertEqual(Decimal(item['unit_cost']), Decimal('1.99'))
        self.assertEqual(Decimal(item['total']), Decimal('19.90'))
        
        #Verify data in the database
        supply = Supply.objects.get(pk=1)
        supply.supplier = self.supplier
        self.assertEqual(supply.cost, Decimal('1.99'))
        self.assertEqual(Log.objects.all().count(), 1)
        log = Log.objects.all()[0]
        self.assertEqual(log.message, "Price change from 12.11USD to 1.99USD for Pattern: Maxx, Col: Blue [Supplier: Zipper World]")
        
    def test_creating_new_po_with_different_currency(self):
        """
        Tests creating a new po via post while also changing the price of a supply
        """
        print '\n'
        logger.debug("Creating new po with a price change")
        print '\n'
        #validate the response
        po = copy.deepcopy(base_purchase_order)
        del po['items'][1]
        po['items'][0]['cost'] = '1.99'
        po['currency'] = 'RMB'
        resp = self.client.post('/api/v1/purchase-order/',
                                data=po,
                                format='json')
        self.assertEqual(resp.status_code, 201, msg=resp)
        resp_obj = resp.data
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(resp_obj['pdf']['url'])
        
        #Verify the returned data
        self.assertEqual(resp_obj['id'], 2)
        self.assertEqual(resp_obj['vat'], 7)
        self.assertEqual(resp_obj['currency'], 'RMB')
        self.assertEqual(Decimal(resp_obj['grand_total']), Decimal('21.30'))
        item = resp_obj['items'][0]
        self.assertEqual(Decimal(item['unit_cost']), Decimal('1.99'))
        self.assertEqual(Decimal(item['total']), Decimal('19.90'))
        
        po = PurchaseOrder.objects.get(pk=2)
        self.assertEqual(po.currency, 'RMB')
        
    def test_updating_the_po(self):
        """
        Tests updating the purchase order
        via a PUT request
        """
        print '\n'
        logger.debug('Updating PO')
        print '\n'
        
        #Verifying po in database
        self.assertEqual(self.po.id, 1)
        self.assertEqual(self.po.items.count(), 1)
        self.assertEqual(self.po.grand_total, Decimal('129.58'))
        self.assertEqual(self.po.order_date.date(), datetime.now().date())
        item = self.po.items.all()[0]
        self.assertEqual(item.id, 1)
        self.assertEqual(item.quantity, 10)
        self.assertEqual(item.total, Decimal('121.1'))
        
        modified_po_data = copy.deepcopy(base_purchase_order)
        del modified_po_data['items'][0]
        modified_po_data['items'][0]['id'] = 1
        modified_po_data['items'][0]['comments'] = 'test change'
        modified_po_data['items'][0]['description'] = "test description change"
        modified_po_data['status'] = 'PROCESSED'
        
        resp = self.client.put('/api/v1/purchase-order/1/',
                                   format='json',
                                   data=modified_po_data)
        
        #Verify the response
        self.assertEqual(resp.status_code, 200, msg=resp)
        po = resp.data
        self.assertEqual(po['id'], 1)
        self.assertEqual(po['supplier']['id'], 1)
        self.assertEqual(po['vat'], 7)
        self.assertEqual(Decimal(po['grand_total']), Decimal('38.88'))
        self.assertEqual(po['discount'], 0)
        self.assertEqual(po['revision'], 1)
        self.assertEqual(len(po['items']), 1)
        #self.assertEqual(po['status'], 'PAID')
        #Check the new pdf
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(po['pdf']['url'])
        
        item2 = po['items'][0]
       
        self.assertEqual(item2['id'], 1)
        self.assertEqual(item2['quantity'], '3.0000000000')
        self.assertEqual(item2['comments'], 'test change')
        self.assertEqual(item2['description'], 'test description change')
        self.assertEqual(Decimal(item2['unit_cost']), Decimal('12.11'))
        self.assertEqual(Decimal(item2['total']), Decimal('36.33'))
        
        #Verify database record
        po = PurchaseOrder.objects.get(pk=1)
        
        self.assertEqual(po.supplier.id, 1)
        self.assertEqual(po.status, 'PROCESSED')
        self.assertEqual(po.order_date.date(), datetime.datetime.now(timezone('Asia/Bangkok')).date())
        self.assertEqual(po.vat, 7)
        self.assertEqual(po.grand_total, Decimal('38.88'))
        self.assertEqual(po.items.count(), 1)
        
        item2 = po.items.all().order_by('id')[0]
        self.assertEqual(item2.id, 1)
        self.assertEqual(item2.description, 'test description change')
        self.assertEqual(item2.comments, 'test change')
        self.assertEqual(item2.quantity, 3)
        self.assertEqual(item2.unit_cost, Decimal('12.11'))
        self.assertEqual(item2.total, Decimal('36.33'))
    
    def test_updating_po_items(self):
        """
        Test updating properties of items in the purchase order
        
        """
        print '\n'
        logger.debug('Updating items')
        print '\n'
        
        modified_po_data = copy.deepcopy(base_purchase_order)
        modified_po_data['status'] = 'PROCESSED'
        modified_po_data['items'][0]['purchasing_units'] = 'set'

        resp = self.client.put('/api/v1/purchase-order/1/', format='json', data=modified_po_data)
        
        po = resp.data
        item1 = po['items'][0]
        #self.assertIn('purchasing_units', item1)
        #self.assertEqual(item1['purchasing_units'], 'set')
        
    def test_updating_po_with_discount(self):
        """
        """
        print '\n'
        logger.debug("Update purchase order with a discount for individual supply")
        print '\n'
        
        #Verify the original po
        self.assertEqual(self.po.id, 1)
        self.assertEqual(self.po.items.count(), 1)
        self.assertEqual(self.po.grand_total, Decimal('129.58'))
        item = self.po.items.all()[0]
        self.assertEqual(item.id, 1)
        self.assertEqual(item.quantity, 10)
        self.assertEqual(item.total, Decimal('121.1'))
        
        modified_po = copy.deepcopy(base_purchase_order)
        modified_po['items'][0]['discount'] = 50
        modified_po['items'][0]['id'] = 1
        modified_po['status'] = 'PROCESSED'
        self.assertEqual(len(modified_po['items']), 2)
        
        resp = self.client.put('/api/v1/purchase-order/1/',
                                format='json',
                                data=modified_po)
        self.assertEqual(resp.status_code, 200, msg=resp)
        resp_obj = resp.data
        self.assertEqual(resp_obj['revision'], 1)
        #Check the new pdf
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(resp_obj['pdf']['url'])
        
        item1 = resp_obj['items'][0]
        item2 = resp_obj['items'][1]
        self.assertEqual(item1['id'], 1)
        self.assertEqual(item1['quantity'], '10.0000000000')
        self.assertEqual(Decimal(item1['unit_cost']), Decimal('12.11'))
        self.assertEqual(Decimal(item1['total']), Decimal('60.55'))
        self.assertEqual(item2['id'], 2)
        self.assertEqual(item2['quantity'], '3.0000000000')
        self.assertEqual(item2['discount'], 5)
        self.assertEqual(Decimal(item2['unit_cost']), Decimal('12.11'))
        self.assertEqual(Decimal(item2['total']), Decimal('34.51'))
        self.assertEqual(Decimal(resp_obj['grand_total']), Decimal('101.72'))
        
        po = PurchaseOrder.objects.get(pk=1)
        item1 = po.items.order_by('id').all()[0]
        self.assertEqual(item1.id, 1)
        self.assertEqual(item1.quantity, Decimal('10.00'))
        self.assertEqual(item1.discount, 50)
        self.assertEqual(item1.unit_cost, Decimal('12.11'))
        self.assertEqual(item1.total, Decimal('60.55'))
        item2 = po.items.order_by('id').all()[1]
        self.assertEqual(item2.id, 2)
        self.assertEqual(item2.quantity, Decimal('3.00'))
        self.assertEqual(item2.unit_cost, Decimal('12.11'))
        self.assertEqual(item2.discount, 5)
        self.assertEqual(item2.total, Decimal('34.51'))
        
    def test_updating_po_with_new_currency(self):
        """
        Test updating the status of supplies and automatically checking in supplies 
        """
        #test original quantity
        
        modified_po = copy.deepcopy(base_purchase_order)
        modified_po['currency'] = 'RMB'
        
        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po)
                               
        self.assertEqual(resp.status_code, 200, msg=resp)
        
        po = resp.data
        
        self.assertEqual(po['currency'], 'RMB')
        
    def test_updating_the_supply_price(self):
        """
        Test updating a po with a new cost for an item
        """
        self.assertEqual(self.po.id, 1)
        self.assertEqual(self.po.items.count(), 1)
        item = self.po.items.all()[0]
        self.assertEqual(item.id, 1)
        self.assertEqual(item.unit_cost, Decimal('12.11'))
        self.assertEqual(Log.objects.all().count(), 0)
        
        modified_po = copy.deepcopy(base_purchase_order)
        modified_po['items'][0]['unit_cost'] = Decimal('10.05')
        modified_po['items'][0]['id'] = 1
        modified_po['status'] = 'PROCESSED'
        del modified_po['items'][1]
        resp = self.client.put('/api/v1/purchase-order/1/',
                                format='json',
                                data=modified_po)
        self.assertEqual(resp.status_code, 200, msg=resp)
        resp_obj = resp.data
        self.assertEqual(resp_obj['revision'], 1)
        #Check the new pdf
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(resp_obj['pdf']['url'])
        
        self.assertEqual(resp_obj['id'], 1)
        self.assertEqual(resp_obj['supplier']['id'], 1)
        self.assertEqual(resp_obj['vat'], 7)
        self.assertEqual(resp_obj['discount'], 0)
        self.assertEqual(resp_obj['revision'], 1)
        self.assertEqual(Decimal(resp_obj['grand_total']), Decimal('107.54'))
        item1 = resp_obj['items'][0]
        self.assertEqual(item1['id'], 2)
        self.assertEqual(item1['quantity'], '10.0000000000')
        self.assertEqual(Decimal(item1['unit_cost']), Decimal('10.05'))
        self.assertEqual(Decimal(item1['total']), Decimal('100.50'))
       
        #Confirm cost change for item and supply in the database
        po = PurchaseOrder.objects.get(pk=1)
        self.assertEqual(po.grand_total, Decimal('107.54'))
        item1 = po.items.order_by('id').all()[0]
        self.assertEqual(item1.id, 1)
        self.assertEqual(item1.quantity, 10)
        self.assertEqual(item1.unit_cost, Decimal('10.05'))
        supply = item1.supply
        supply.supplier = po.supplier
        self.assertEqual(supply.cost, Decimal('10.05'))
        
        self.assertEqual(Log.objects.all().count(), 1)
        log = Log.objects.all()[0]
        self.assertEqual(log.cost, Decimal('10.05'))
        self.assertEqual(log.supply, supply)
        self.assertEqual(log.supplier, po.supplier)
        self.assertEqual(log.message, "Price change from 12.11USD to 10.05USD for Pattern: Maxx, Col: Blue [Supplier: Zipper World]")
       
    def test_updating_item_status(self):
        """
        Test updating the status of supplies and automatically checking in supplies 
        """
        #test original quantity
        self.assertEqual(self.supply1.quantity, 10)
        self.assertEqual(self.supply2.quantity, 10)
        
        modified_po = copy.deepcopy(base_purchase_order)
        modified_po['status'] = 'Received'
        modified_po['items'][0]['id'] = 1
        #modified_po['items'][0]['status'] = 'Receieved'
            
        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po)
                               
        self.assertEqual(resp.status_code, 200, msg=resp)
        
        po = resp.data
        
        self.assertEqual(Supply.objects.get(pk=1).quantity, 20)
        
    def test_updating_the_project(self):
        """
        Tests updating the project, phase, and room of a purchase order
        """
        modified_po = copy.deepcopy(base_purchase_order)
        
        
    def test_updating_to_receive_items(self):
        """
        Test updating the status of the po in order to to receive it
        
        When a purchase order is received, the items received should automatically be added to the 
        supply inventory quantity
        """
        modified_po = copy.deepcopy(base_purchase_order)
        modified_po['items'][0]['id'] = 1
        modified_po['items'][0]['status'] = 'RECEIVED'
        modified_po['status'] = 'RECEIVED'
        self.assertEqual(Supply.objects.get(pk=1).quantity, 10)
        
        resp = self.client.put('/api/v1/purchase-order/1/', format='json', data=modified_po)
        
        self.assertEqual(resp.status_code, 200, msg=resp)
        
        po_data = resp.data
        self.assertEqual(po_data['id'], 1)
        self.assertEqual(po_data['status'], 'RECEIVED')
        
        item1 = po_data['items'][0]
        self.assertEqual(item1['id'], 1)
        self.assertEqual(item1['status'], 'RECEIVED')
        
        #Test database values
        po = PurchaseOrder.objects.get(pk=1)
        self.assertEqual(po.id, 1)
        self.assertEqual(po.status, 'RECEIVED')
        for item in po.items.all():
            self.assertEqual(item.status, "RECEIVED")
            
        supply = Supply.objects.get(pk=1)
        self.assertEqual(supply.quantity, 20)
        log = Log.objects.all().order_by('-id')[0]
        self.assertEqual(log.action, "ADD")
        self.assertEqual(log.quantity, 10)
        self.assertEqual(log.supplier.id, 1)
        self.assertEqual(log.message, "Received 10m of Pattern: Maxx, Col: Blue from Zipper World")
Exemplo n.º 19
0
class FabricAPITestCase(APITestCase):
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(FabricAPITestCase, self).setUp()

        self.create_user()
        self.client.login(username="******", password="******")

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supply = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)

        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()

    def create_user(self):
        self.user = User.objects.create_user("test", "*****@*****.**", "test")
        self.ct = ContentType(app_label="supplies")
        self.ct.save()
        self._create_and_add_permission("view_cost", self.user)
        self._create_and_add_permission("change_fabric", self.user)
        self._create_and_add_permission("add_fabric", self.user)
        self._create_and_add_permission("add_quantity", self.user)
        self._create_and_add_permission("subtract_quantity", self.user)

    def _create_and_add_permission(self, codename, user):
        p = Permission(content_type=self.ct, codename=codename)
        p.save()
        user.user_permissions.add(p)

    def _remove_permission(self, codename):
        self.user.user_permissions.remove(Permission.objects.get(codename=codename, content_type=self.ct))

    def test_get_list(self):
        """
        Tests that a standard get call works.
        """

        # Testing standard GET
        resp = self.client.get("/api/v1/fabric/")
        self.assertEqual(resp.status_code, 200)

        # Tests the returned data
        resp_obj = resp.data
        self.assertIn("results", resp_obj)
        self.assertEqual(len(resp_obj["results"]), 2)

    def test_get(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        resp = self.client.get("/api/v1/fabric/1/")
        self.assertEqual(resp.status_code, 200)

        obj = resp.data
        # self.assertEqual(float(obj['cost']), float('100'))

    def test_get_without_price(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        # Delete the view cost permission from the user
        self.user.user_permissions.remove(Permission.objects.get(codename="view_cost", content_type=self.ct))

        # tests the response
        resp = self.client.get("/api/v1/fabric/1/")
        self.assertEqual(resp.status_code, 200)

        # Tests the data returned
        obj = resp.data
        self.assertNotIn("cost", obj)

    def test_post(self):
        """
        Tests posting to the server
        """
        # Test creating an objects.
        self.assertEqual(Supply.objects.count(), 2)
        resp = self.client.post("/api/v1/fabric/", format="json", data=base_fabric)
        self.assertEqual(resp.status_code, 201, msg=resp)

        # Tests the dat aturned
        obj = resp.data
        self.assertEqual(obj["id"], 3)
        self.assertEqual(obj["width"], "100.00")
        self.assertEqual(obj["depth"], "0.00")
        self.assertEqual(obj["height"], "300.00")
        self.assertEqual(obj["description"], u"Max Col: Hot Pink")
        self.assertNotIn("reference", obj)
        self.assertNotIn("cost", obj)
        self.assertIn("suppliers", obj)

        supplier = obj["suppliers"][0]
        self.assertEqual(supplier["reference"], "A2234")
        self.assertEqual(int(supplier["cost"]), 100)

    def test_put(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data["cost"] = "111"
        modified_data["color"] = "Aqua"
        modified_data["pattern"] = "Stripes"
        # Tests the api and the response
        self.assertEqual(Supply.objects.count(), 2)
        resp = self.client.put("/api/v1/fabric/1/", format="json", data=modified_data)

        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 2)

        # Tests the returned data
        obj = resp.data
        self.assertEqual(obj["color"], "Aqua")
        self.assertEqual(obj["pattern"], "Stripes")

    def test_put_add_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data["quantity"] = "14"
        modified_data["color"] = "Aqua"
        modified_data["pattern"] = "Stripes"

        # Tests the api and the response
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("10.8"))
        resp = self.client.put("/api/v1/fabric/1/", format="json", data=modified_data)
        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("14"))

        # Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj["quantity"]), float("14"))

    def test_put_subtract_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data["quantity"] = "8"
        modified_data["color"] = "Aqua"
        modified_data["pattern"] = "Stripes"

        # Tests the api and the response
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("10.8"))
        resp = self.client.put("/api/v1/fabric/1/", format="json", data=modified_data)

        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("8"))

        # Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj["quantity"]), float("8"))

    @unittest.skip("ok")
    def test_put_add_quantity_fail(self):
        """
        Tests an unauthorized addition of quantity
        """
        # Delete permissions
        self._remove_permission("add_quantity")

        # Create new data
        modified_data = base_fabric.copy()
        modified_data["quantity"] = "20"

        # Tests the api and response
        resp = self.client.put("/api/v1/fabric/1/", format="json", data=modified_data)
        self.assertEqual(Fabric.objects.get(pk=1).quantity, float("10.8"))
        # Tests the data retured
        obj = resp.data
        self.assertEqual(float(obj["quantity"]), float("10.8"))

    @unittest.skip("ok")
    def test_put_subtract_quantity_fail(self):
        """
        Tests an unauthorized addition of quantity
        """
        # Delete permissions
        self._remove_permission("subtract_quantity")

        # Create new data
        modified_data = base_fabric.copy()
        modified_data["quantity"] = "6"

        # Tests the api and response
        resp = self.client.put("/api/v1/fabric/1/", format="json", data=modified_data)
        self.assertEqual(Fabric.objects.get(pk=1).quantity, float("10.8"))
        # Tests the data retured
        obj = resp.data
        self.assertEqual(float(obj["quantity"]), float("10.8"))
Exemplo n.º 20
0
def work():
    data = []
    review = []
    supplier = Supplier.objects.get(name__icontains="blue international")
    with open("/Users/Charlie/Sites/employee/backend/blue-inter.csv",
              'r') as f:
        reader = csv.reader(f)
        for row in reader:
            data.append({
                'reference': row[0],
                'description': row[1],
                'cost': row[2],
                'units': row[3]
            })

    for index, d in enumerate(data):
        for key in d.keys():
            try:
                d[key] = d[key].encode('utf-8')
            except UnicodeDecodeError as e:
                pass

            if key == "cost":
                try:
                    d[key] = Decimal(d[key].replace(',', ''))
                except InvalidOperation as e:
                    review.append(data.pop(index))

            if key == "units":
                if not d[key]:
                    review.append(data.pop(index))

    for index, d in enumerate(data):
        try:
            try:
                supply = Supply.objects.get(description=d['description'])
            except Supply.DoesNotExist:
                supply = Supply()

            supply.description = d['description']
            supply.units = d['units']
            supply.full_clean()
            supply.save()

            try:
                product = Product.objects.get(supply=supply)
            except Product.DoesNotExist:
                product = Product(supply=supply, supplier=supplier)

            product.supplier = supplier
            product.supply = supply
            product.reference = d['reference']
            product.cost = d['cost']
            product.purchasing_units = d['units']
            product.full_clean()
            product.save()

        except ValidationError as e:
            print e
            review.append(data.pop(index))

        assert Supply.objects.filter(description=d['description']).count() == 1

    with open('blue-inter-review.csv', 'w') as f:
        fieldnames = ['reference', 'description', 'cost', 'units']
        writer = csv.DictWriter(f)
        writer.write_header()
        for d in review:
            writer.writerow(d)

    assert supplier.supplies.all().count() == len(data)
Exemplo n.º 21
0
class SupplyAPITestCase(APITestCase):
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(SupplyAPITestCase, self).setUp()

        self.create_user()
        self.client.login(username="******", password="******")

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supplier2 = Supplier.objects.create(**base_supplier)
        self.supply = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply2.pk)
        self.supply3 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply3.pk)
        self.supply4 = Supply.create(**base_supply)
        self.assertIsNotNone(self.supply4.pk)

        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()

        self.employee = Employee(first_name="John", last_name="Smith")
        self.employee.save()

    def create_user(self):
        self.user = User.objects.create_user("test", "*****@*****.**", "test")
        self.ct = ContentType(app_label="supplies")
        self.ct.save()
        self._create_and_add_permission("view_cost", self.user)
        self._create_and_add_permission("change_supply", self.user)
        self._create_and_add_permission("add_supply", self.user)
        self._create_and_add_permission("add_quantity", self.user)
        self._create_and_add_permission("subtract_quantity", self.user)

    def _create_and_add_permission(self, codename, user):
        p = Permission(content_type=self.ct, codename=codename)
        p.save()
        user.user_permissions.add(p)

    def test_get_list(self):
        """
        Tests that a standard get call works.
        """

        # Testing standard GET
        resp = self.client.get("/api/v1/supply/")
        self.assertEqual(resp.status_code, 200)

        # Tests the returned data
        resp_obj = resp.data
        self.assertIn("results", resp_obj)
        self.assertEqual(len(resp_obj["results"]), 4)

    def test_get(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        resp = self.client.get("/api/v1/supply/1/")
        self.assertEqual(resp.status_code, 200)

        obj = resp.data
        # self.assertEqual(Decimal(obj['cost']), Decimal('100'))
        self.assertIn("description", obj)
        self.assertEqual(obj["description"], "test")
        self.assertIn("type", obj)
        self.assertEqual(obj["type"], "wood")

        resp = self.client.get("/api/v1/supply/1/?country=TH")
        self.assertEqual(resp.status_code, 200)
        obj = resp.data
        self.assertEqual(obj["quantity"], 10.8)
        self.assertIn("suppliers", obj)
        self.assertEqual(len(obj["suppliers"]), 1)
        supplier = obj["suppliers"][0]

    def stest_get_log(self):
        """
        Tests gettings the log for all the supplies
        """

        resp = self.client.get("/api/v1/supply/log/")
        # self.assertEqual(resp.status_code, 200)
        obj = resp.data
        # self.assertIsInstance(obj, list)

    def test_get_without_price(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        # Delete the view cost permission from the user
        self.user.user_permissions.remove(Permission.objects.get(codename="view_cost", content_type=self.ct))

        # tests the response
        resp = self.client.get("/api/v1/supply/1/")
        self.assertEqual(resp.status_code, 200)

        # Tests the data returned
        obj = resp.data
        self.assertNotIn("cost", obj)

    def test_get_types(self):
        """
        Tests getting the different types
        used to describe supplies
        """
        resp = self.client.get("/api/v1/supply/type/")
        # self.assertEqual(resp.status_code, 200)
        type_list = resp.data
        # self.assertIn('wood', type_list)

    def test_post_single_supplier(self):
        """
        Tests posting to the server
        """
        # Test creating an objects.
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.post("/api/v1/supply/", format="json", data=base_supply)
        self.assertEqual(resp.status_code, 201, msg=resp)

        # Tests the dat aturned
        obj = resp.data
        self.assertEqual(obj["id"], 5)
        self.assertEqual(obj["width"], "100.00")
        self.assertEqual(obj["depth"], "200.00")
        self.assertEqual(obj["height"], "300.00")
        self.assertEqual(obj["description"], "test")
        self.assertEqual(obj["height_units"], "yd")
        self.assertEqual(obj["width_units"], "m")
        self.assertEqual(obj["notes"], "This is awesome")
        self.assertIn("type", obj)
        self.assertEqual(obj["type"], "wood")
        self.assertIn("suppliers", obj)
        self.assertEqual(len(obj["suppliers"]), 1)

        # Test Supplier
        supplier = obj["suppliers"][0]
        self.assertEqual(supplier["reference"], "A2234")
        self.assertEqual(supplier["cost"], Decimal("100"))

        # TEsts the object created
        supply = Supply.objects.order_by("-id").all()[0]
        supply.supplier = supply.suppliers.all()[0]
        self.assertEqual(supply.id, 5)
        self.assertEqual(supply.width, 100)
        self.assertEqual(supply.depth, 200)
        self.assertEqual(supply.height, 300)
        # self.assertEqual(supply.reference, 'A2234')
        self.assertEqual(supply.description, "test")
        # self.assertEqual(supply.cost, 100)
        self.assertEqual(supply.height_units, "yd")
        self.assertEqual(supply.width_units, "m")
        self.assertEqual(supply.notes, "This is awesome")
        self.assertIsNotNone(supply.type)
        self.assertEqual(supply.type, "wood")
        self.assertIsNotNone(supply.suppliers)
        self.assertEqual(supply.suppliers.count(), 1)

    def test_posting_with_custom_type(self):
        """
        Testing creating a new resource via POST 
        that has a custom type
        """
        # Testing returned types pre POST
        resp0 = self.client.get("/api/v1/supply/type/", format="json")
        self.assertEqual(resp0.status_code, 200, msg=resp0)
        type_list = resp0.data
        self.assertNotIn("egg", type_list)
        self.assertIn("wood", type_list)
        self.assertEqual(len(type_list), 1)

        # POST
        modified_supply = base_supply.copy()
        modified_supply["type"] = "egg"
        resp = self.client.post("/api/v1/supply/", format="json", data=modified_supply)
        self.assertEqual(resp.status_code, 201)

        # Tests the response
        obj = resp.data
        self.assertIn("type", obj)
        self.assertNotIn("custom-type", obj)
        self.assertEqual(obj["type"], "egg")

        """
        resp2 = self.client.get('/api/v1/supply/type/', format='json')
        self.assertHttpOK(resp2)
        type_list = self.deserialize(resp2)
        self.assertIn('egg', type_list)
        self.assertIn('wood', type_list)
        self.assertEqual(len(type_list), 2)
        """

    def test_put(self):
        """
        Tests adding quantity to the item
        """

        # Validate original data
        supply = Supply.objects.get(pk=1)
        supply.country = "TH"
        self.assertEqual(supply.quantity, 10.8)
        self.assertEqual(Log.objects.all().count(), 0)

        # Prepare modified data for PUT
        modified_data = base_supply.copy()
        modified_data["description"] = "new"
        modified_data["type"] = "Glue"
        modified_data["quantity"] = "11"

        # Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.put("/api/v1/supply/1/?country=TH", format="json", data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)

        # Tests the returned data
        obj = resp.data
        self.assertEqual(obj["type"], "Glue")
        self.assertEqual(float(obj["quantity"]), 11)
        self.assertEqual(obj["description"], "new")
        self.assertFalse(obj.has_key("quantity_th"))
        self.assertFalse(obj.has_key("quantity_kh"))

        # Tests the resource in the database
        supply = Supply.objects.get(pk=1)
        supply.country = "TH"
        self.assertEqual(supply.type, "Glue")
        self.assertEqual(supply.country, "TH")
        self.assertEqual(supply.description, "new")
        self.assertEqual(supply.quantity, 11)
        self.assertEqual(Log.objects.all().count(), 1)
        log = Log.objects.all()[0]
        self.assertEqual(log.action, "ADD")
        self.assertEqual(log.quantity, Decimal("0.2"))
        self.assertEqual(log.message, "Added 0.2ml to new")

    def test_put_without_quantity_change(self):
        """
        Tests adding quantity to the item
        """

        # Validate original data
        supply = Supply.objects.get(pk=1)
        supply.country = "TH"
        self.assertEqual(supply.quantity, 10.8)
        self.assertEqual(Log.objects.all().count(), 0)

        # Prepare modified data for PUT
        modified_data = base_supply.copy()
        modified_data["description"] = "new"
        modified_data["type"] = "Glue"
        modified_data["quantity"] = "10.8"
        modified_data["width_units"] = "cm"
        modified_data["depth_units"] = "cm"

        # Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.put("/api/v1/supply/1/?country=TH", format="json", data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)

        # Tests the returned data
        obj = resp.data
        self.assertEqual(obj["type"], "Glue")
        self.assertEqual(float(obj["quantity"]), 10.8)
        self.assertEqual(obj["description"], "new")
        self.assertEqual(obj["width_units"], "cm")
        self.assertEqual(obj["depth_units"], "cm")
        self.assertFalse(obj.has_key("quantity_th"))
        self.assertFalse(obj.has_key("quantity_kh"))

        # Tests the resource in the database
        supply = Supply.objects.get(pk=1)
        supply.country = "TH"
        self.assertEqual(supply.type, "Glue")
        self.assertEqual(supply.country, "TH")
        self.assertEqual(supply.description, "new")
        self.assertEqual(supply.quantity, 10.8)

        self.assertEqual(Log.objects.all().count(), 0)

    def test_put_subtracting_quantity_to_0(self):
        """
        Tests adding quantity to the item
        """

        # Validate original data
        supply = Supply.objects.get(pk=1)
        supply.country = "TH"
        supply.quantity = 1
        supply.save()

        self.assertEqual(supply.quantity, 1)
        self.assertEqual(Log.objects.all().count(), 0)

        # Prepare modified data for PUT
        modified_data = base_supply.copy()
        modified_data["description"] = "new"
        modified_data["type"] = "Glue"
        modified_data["quantity"] = "0"

        # Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        resp = self.client.put("/api/v1/supply/1/?country=TH", format="json", data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)

        # Tests the returned data
        obj = resp.data
        self.assertEqual(obj["quantity"], 0)

        self.assertFalse(obj.has_key("quantity_th"))
        self.assertFalse(obj.has_key("quantity_kh"))

        # Tests the resource in the database
        supply = Supply.objects.get(pk=1)
        supply.country = "TH"
        self.assertEqual(supply.quantity, 0)

        log = Log.objects.all().order_by("-id")[0]
        self.assertEqual(Log.objects.all().count(), 1)
        self.assertEqual(log.quantity, 1)
        self.assertEqual(log.action, "SUBTRACT")

    @unittest.skip("Not yet implemented")
    def test_add(self):
        """
        Tests adding a quantity
        to the specific url
        """
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("10.8"))
        resp = self.client.post("/api/v1/supply/1/add/?quantity=5", format="json")
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("15.8"))

    @unittest.skip("Not yet implemented")
    def test_subract(self):
        """
        Tests adding a quantity
        to the specific url
        """
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("10.8"))
        resp = self.client.post("/api/v1/supply/1/subtract/?quantity=5", format="json")
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("5.8"))

    def test_put_add_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data["quantity"] = "14"
        modified_data["description"] = "new"

        # Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("10.8"))
        resp = self.client.put("/api/v1/supply/1/", format="json", data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("14"))
        self.assertEqual(Supply.objects.get(pk=1).description, "new")

        # Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj["quantity"]), float("14"))

    def test_put_subtract_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data["quantity"] = "8"

        # Tests the api and the response
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("10.8"))
        resp = self.client.put("/api/v1/supply/1/", format="json", data=modified_data)

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Supply.objects.count(), 4)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float("8"))

        # Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj["quantity"]), float("8"))

    def test_put_to_create_new_product(self):
        """
        Tests adding a new supplier/product to the supply
        """
        logger.debug("\n\nTest creating a new supply/product via PUT\n")
        modified_data = copy.deepcopy(base_supply)
        modified_data["suppliers"] = [
            {"id": 1, "supplier": {"id": 1}, "reference": "BOO", "cost": "123.45"},
            {
                "reference": "A4",
                "cost": "19.99",
                "purchasing_units": "ml",
                "quantity_per_purchasing_unit": 4,
                "supplier": {"id": 2},
            },
        ]

        resp = self.client.put("/api/v1/supply/1/", format="json", data=modified_data)

        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 4)

        obj = resp.data
        self.assertIn("suppliers", obj)
        self.assertEqual(len(obj["suppliers"]), 2)
        supplier1 = obj["suppliers"][0]
        self.assertEqual(supplier1["reference"], "BOO")
        self.assertEqual(supplier1["cost"], Decimal("123.45"))

        supplier2 = obj["suppliers"][1]
        self.assertEqual(supplier2["reference"], "A4")
        self.assertEqual(supplier2["cost"], Decimal("19.99"))
        self.assertEqual(supplier2["purchasing_units"], "ml")
        self.assertEqual(supplier2["quantity_per_purchasing_unit"], Decimal("4"))
        self.assertEqual(supplier2["supplier"]["id"], 2)

    def test_updating_multiple_supplies(self):
        """
        Test that we can update the quantities of multiple supplies
        """
        data = [
            {"id": 1, "description": "poooo", "quantity": 9, "employee": {"id": 1}},
            {"id": 2, "quantity": 12.3, "employee": {"id": 1}},
        ]

        resp = self.client.put("/api/v1/supply/", format="json", data=data)
        self.assertEqual(resp.status_code, 200, msg=resp)
        supplies = resp.data

        supply1 = supplies[0]
        self.assertEqual(supply1["quantity"], 9)
        self.assertEqual(supply1["description"], u"poooo")
        supply1_obj = Supply.objects.get(pk=1)
        self.assertEqual(supply1_obj.quantity, 9)

        supply2 = supplies[1]
        self.assertEqual(supply2["quantity"], Decimal("12.3"))
        supply2_obj = Supply.objects.get(pk=2)
        self.assertEqual(supply2_obj.quantity, 12.3)

        log1 = Log.objects.all()[0]
        self.assertEqual(log1.action, "SUBTRACT")
        self.assertEqual(log1.quantity, Decimal("1.8"))
        self.assertIsNotNone(log1.employee)
        self.assertEqual(log1.employee.id, 1)
        self.assertEqual(log1.employee.first_name, "John")
        self.assertEqual(log1.employee.last_name, "Smith")

        log2 = Log.objects.all()[1]
        self.assertEqual(log2.action, "ADD")
        self.assertEqual(log2.quantity, Decimal("1.5"))
        self.assertIsNotNone(log2.employee)
        self.assertEqual(log2.employee.id, 1)
        self.assertEqual(log2.employee.first_name, "John")
        self.assertEqual(log2.employee.last_name, "Smith")
Exemplo n.º 22
0
class PurchaseOrderTest(APITestCase):
    """
    Tests the Purchase Order
    """
    def setUp(self):
        """
        Set up dependent objects
        """
        super(PurchaseOrderTest, self).setUp()

        self.ct = ContentType(app_label="po")
        self.ct.save()
        self.p = Permission(codename="add_purchaseorder", content_type=self.ct)
        self.p.save()
        self.p2 = Permission(codename="change_purchaseorder",
                             content_type=self.ct)
        self.p2.save()
        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(
            self.username, '*****@*****.**', self.password)
        self.user.save()
        self.user.user_permissions.add(self.p)
        self.user.user_permissions.add(self.p2)
        self.client.login(username=self.username, password=self.password)
        self.client.force_authenticate(self.user)

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(**base_address)
        self.address.contact = self.supplier
        self.address.save()
        self.contact = SupplierContact(name='test',
                                       email='*****@*****.**',
                                       telephone=1234,
                                       primary=True)
        self.contact.supplier = self.supplier
        self.contact.save()

        # Create Custom Supply
        # not implemented

        # Create Fabric
        self.supply = Fabric.create(**base_fabric)

        #self.supply.units = "m^2"
        self.supply.save()
        self.supply1 = self.supply

        self.product = Product(supply=self.supply,
                               supplier=self.supplier,
                               cost=base_fabric['unit_cost'],
                               purchasing_units='m')
        self.product.save()
        self.supply2 = Fabric.create(**base_fabric2)
        self.supply2.discount = 5
        self.supply2.save()
        self.product2 = Product(supply=self.supply2,
                                supplier=self.supplier,
                                cost=base_fabric['unit_cost'])
        self.product2.save()
        self.supply1.supplier = self.supplier
        self.supply2.supplier = self.supplier

        #Create supply with no target item
        self.supply3 = Supply.objects.create(description='test supply')
        self.supply3.id = 203
        self.supply3.save()

        #Create a project
        self.project = Project()
        self.project.codename = 'MC House'
        self.project.save()

        self.po = PurchaseOrder()
        self.po.employee = self.user
        self.po.supplier = self.supplier
        self.po.terms = self.supplier.terms
        self.po.vat = 7
        self.order_date = datetime.datetime(2017,
                                            1,
                                            15,
                                            15,
                                            30,
                                            0,
                                            0,
                                            tzinfo=timezone('Asia/Bangkok'))
        self.po.order_date = self.order_date
        self.po.receive_date = datetime.datetime.now()
        self.po.save()
        #self.po.create_and_upload_pdf()

        self.item = Item.create(supplier=self.supplier,
                                id=1,
                                **base_purchase_order['items'][0])
        self.item.purchase_order = self.po
        self.item.save()

        self.po.calculate_total()
        self.po.save()

    def test_get_list(self):
        """
        Tests getting a list of po's via GET
        """
        #Validate the response
        resp = self.client.get('/api/v1/purchase-order/', format='json')
        self.assertEqual(resp.status_code, 200)

        #Validate the returned data
        resp = resp.data
        self.assertIsInstance(resp, list)
        self.assertEqual(len(resp), 1)

    def test_get(self):
        """
        Tests getting a single resource via GET
        """
        #Validate the response
        resp = self.client.get('/api/v1/purchase-order/1/')
        self.assertEqual(resp.status_code, 200)

        #Validate the returned data
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertEqual(obj['terms'], '0/net')
        self.assertEqual(obj['revision'], 0)

        #Test items
        self.assertIn('items', obj)
        self.assertEqual(len(obj['items']), 1)
        item1 = obj['items'][0]
        #self.assertIn('purchasing_units', item1)
        #self.assertEqual(item1['purchasing_units'], 'm')

    def test_get_with_pdf(self):
        """
        Tests getting a resource with the pdf
        """
        self.skipTest("")
        self.po.create_and_upload_pdf()

        resp = self.client.get('/api/v1/purchase-order/1/')
        self.assertEqual(resp.status_code, 200)

        obj = resp.data
        self.assertIn('pdf', obj)
        self.assertIn('url', obj['pdf'])
        self.assertIsNotNone(obj['pdf']['url'])

    def test_post(self):
        """
        Tests creating a new resource via POST
        """

        print '\n'
        logger.debug("Creating new po")
        print '\n'

        #validate the response
        resp = self.client.post('/api/v1/purchase-order/',
                                data=base_purchase_order,
                                format='json')
        self.assertEqual(resp.status_code, 201, msg=resp)

        #Validate the data returned
        obj = resp.data
        self.assertEqual(obj['id'], 2)
        self.assertIsNotNone(obj['items'])
        self.assertIsInstance(obj['items'], list)
        self.assertEqual(len(obj['items']), 2)
        self.assertEqual(obj['currency'], 'USD')
        self.assertIn('project', obj)
        self.assertIsInstance(obj['project'], dict)
        self.assertEqual(obj['project']['id'], 1)
        self.assertEqual(obj['project']['codename'], 'MC House')

        #validate the resource in the database
        po = PurchaseOrder.objects.get(pk=2)
        self.assertIsInstance(po.project, Project)
        #self.assertIsNotNone(obj['pdf'])
        #self.assertIsNotNone(obj['pdf']['url'])
        self.items = po.items.all().order_by('id')
        self.item1 = self.items[0]
        self.item2 = self.items[1]
        self.assertIsInstance(self.item1, Item)
        self.assertIsInstance(self.item1.supply, Supply)
        self.assertEqual(self.item1.supply.id, 1)
        self.assertEqual(self.item1.unit_cost, Decimal('12.11'))
        self.assertEqual(self.item1.quantity, 10)
        self.assertEqual(self.item1.total, Decimal('121.1'))
        self.assertIsInstance(self.item2, Item)
        self.assertIsInstance(self.item2.supply, Supply)
        self.assertEqual(self.item2.supply.id, 2)
        self.assertEqual(self.item2.unit_cost, Decimal('12.11'))
        self.assertEqual(self.item2.quantity, 3)
        self.assertEqual(self.item2.total, Decimal('34.51'))

        self.assertEqual(Project.objects.count(), 1)
        project = Project.objects.all()[0]
        self.assertIsInstance(project, Project)
        self.assertEqual(project.id, 1)
        self.assertEqual(project.codename, 'MC House')

    def test_post_with_new_project(self):
        """
        Tests creating a new resource via POST
        """
        print '\n'
        logger.debug("Creating new po with a project")
        print '\n'

        #validate the response
        po = base_purchase_order.copy()
        po['project'] = {'codename': 'Ladawan'}
        po['currency'] = 'RMB'
        resp = self.client.post('/api/v1/purchase-order/',
                                data=po,
                                format='json')
        self.assertEqual(resp.status_code, 201, msg=resp)

        #Validate the data returned
        obj = resp.data
        self.assertEqual(obj['id'], 2)
        self.assertIsNotNone(obj['items'])
        self.assertIsInstance(obj['items'], list)
        self.assertEqual(len(obj['items']), 2)
        self.assertIn('project', obj)
        self.assertIsInstance(obj['project'], dict)
        self.assertEqual(obj['project']['id'], 2)
        self.assertEqual(obj['project']['codename'], 'Ladawan')
        self.assertEqual(obj['currency'], 'RMB')

        #validate the resource in the database
        po = PurchaseOrder.objects.get(pk=2)
        self.assertIsInstance(po.project, Project)
        #self.assertIsNotNone(obj['pdf'])
        #self.assertIsNotNone(obj['pdf']['url'])
        self.items = po.items.all().order_by('id')
        self.item1 = self.items[0]
        self.item2 = self.items[1]
        self.assertIsInstance(self.item1, Item)
        self.assertIsInstance(self.item1.supply, Supply)
        self.assertEqual(self.item1.supply.id, 1)
        self.assertEqual(self.item1.unit_cost, Decimal('12.11'))
        self.assertEqual(self.item1.quantity, 10)
        self.assertEqual(self.item1.total, Decimal('121.1'))
        self.assertIsInstance(self.item2, Item)
        self.assertIsInstance(self.item2.supply, Supply)
        self.assertEqual(self.item2.supply.id, 2)
        #self.assertEqual(self.item2.unit_cost, Decimal('11.50'))
        self.assertEqual(self.item2.quantity, 3)
        self.assertEqual(self.item2.total, Decimal('34.51'))

        project = po.project
        self.assertEqual(Project.objects.all().count(), 2)
        self.assertIsInstance(project, Project)
        self.assertEqual(project.id, 2)
        self.assertEqual(project.codename, 'Ladawan')

    def test_creating_new_po_with_price_change(self):
        """
        Tests creating a new po via post while also changing the price of a supply
        """
        print '\n'
        logger.debug("Creating new po with a price change")
        print '\n'
        #validate the response
        po = copy.deepcopy(base_purchase_order)
        del po['items'][1]
        po['items'][0]['cost'] = '1.99'
        po['items'][0]['unit_cost'] = '1.99'
        resp = self.client.post('/api/v1/purchase-order/',
                                data=po,
                                format='json')
        self.assertEqual(resp.status_code, 201, msg=resp)
        resp_obj = resp.data
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(resp_obj['pdf']['url'])

        #Verify the returned data
        self.assertEqual(resp_obj['id'], 2)
        self.assertEqual(resp_obj['vat'], 7)
        self.assertEqual(Decimal(resp_obj['grand_total']), Decimal('21.29'))
        item = resp_obj['items'][0]
        self.assertEqual(Decimal(item['unit_cost']), Decimal('1.99'))
        self.assertEqual(Decimal(item['total']), Decimal('19.90'))

        #Verify data in the database
        supply = Supply.objects.get(pk=1)
        supply.supplier = self.supplier
        self.assertEqual(supply.cost, Decimal('1.99'))
        self.assertEqual(Log.objects.all().count(), 1)
        log = Log.objects.all()[0]
        self.assertEqual(
            log.message,
            "Price change from 12.11USD to 1.99USD for Pattern: Maxx, Col: Blue [Supplier: Zipper World]"
        )

    def test_creating_new_po_with_different_currency(self):
        """
        Tests creating a new po via post while also changing the price of a supply
        """
        print '\n'
        logger.debug("Creating new po with a price change")
        print '\n'
        #validate the response
        po = copy.deepcopy(base_purchase_order)
        del po['items'][1]
        po['items'][0]['cost'] = '1.99'
        po['currency'] = 'RMB'
        resp = self.client.post('/api/v1/purchase-order/',
                                data=po,
                                format='json')
        self.assertEqual(resp.status_code, 201, msg=resp)
        resp_obj = resp.data
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(resp_obj['pdf']['url'])

        #Verify the returned data
        self.assertEqual(resp_obj['id'], 2)
        self.assertEqual(resp_obj['vat'], 7)
        self.assertEqual(resp_obj['currency'], 'RMB')
        self.assertEqual(Decimal(resp_obj['grand_total']), Decimal('21.29'))
        item = resp_obj['items'][0]
        self.assertEqual(Decimal(item['unit_cost']), Decimal('1.99'))
        self.assertEqual(Decimal(item['total']), Decimal('19.90'))

        po = PurchaseOrder.objects.get(pk=2)
        self.assertEqual(po.currency, 'RMB')

    def test_updating_the_po(self):
        """
        Tests updating the purchase order
        via a PUT request
        """
        print '\n'
        logger.debug('Updating PO')
        print '\n'

        #Verifying po in database
        self.assertEqual(self.po.id, 1)
        self.assertEqual(self.po.items.count(), 1)
        self.assertEqual(self.po.grand_total, Decimal('129.58'))
        self.assertEqual(
            timezone('Asia/Bangkok').normalize(self.po.order_date).date(),
            datetime.datetime.now().date())
        item = self.po.items.all()[0]
        self.assertEqual(item.id, 1)
        self.assertEqual(item.quantity, 10)
        self.assertEqual(item.total, Decimal('121.1'))

        modified_po_data = copy.deepcopy(base_purchase_order)
        del modified_po_data['items'][1]
        modified_po_data['id'] = 1
        modified_po_data['items'][0]['id'] = 1
        modified_po_data['items'][0]['comments'] = 'test change'
        modified_po_data['items'][0]['quantity'] = 3
        modified_po_data['items'][0]['description'] = 'test description change'

        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po_data)

        #Verify the response
        self.assertEqual(resp.status_code, 200, msg=resp)
        po = resp.data
        self.assertEqual(po['id'], 1)
        self.assertEqual(po['supplier']['id'], 1)
        self.assertEqual(po['vat'], 7)
        self.assertEqual(Decimal(po['grand_total']), Decimal('38.87'))
        self.assertEqual(po['discount'], 0)
        self.assertEqual(po['revision'], 1)
        self.assertEqual(len(po['items']), 1)
        #self.assertEqual(po['status'], 'PAID')
        #Check the new pdf
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(po['pdf']['url'])

        item2 = po['items'][0]

        self.assertEqual(item2['id'], 1)
        self.assertEqual(item2['quantity'], Decimal('3.0000000000'))
        self.assertEqual(item2['comments'], 'test change')
        self.assertEqual(item2['description'], 'test description change')
        self.assertEqual(Decimal(item2['unit_cost']), Decimal('12.11'))
        self.assertEqual(Decimal(item2['total']), Decimal('36.33'))

        #Verify database record
        po = PurchaseOrder.objects.get(pk=1)

        self.assertEqual(po.supplier.id, 1)
        #self.assertEqual(timezone('Asia/Bangkok').normalize(po.order_date), datetime.datetime.now().date())
        self.assertEqual(po.vat, 7)
        self.assertEqual(po.grand_total, Decimal('38.87'))
        self.assertEqual(po.items.count(), 1)

        item2 = po.items.all().order_by('id')[0]
        self.assertEqual(item2.id, 1)
        self.assertEqual(item2.description, 'test description change')
        self.assertEqual(item2.comments, 'test change')
        self.assertEqual(item2.quantity, 3)
        self.assertEqual(item2.unit_cost, Decimal('12.11'))
        self.assertEqual(item2.total, Decimal('36.33'))

    def test_adding_a_new_item_with_no_supply(self):
        """
        Test adding a new item to the purchase order with no previous supply or product"
        """
        print '\n'
        logger.debug('Add a new item to a current PO via PUT')
        print '\n'

        #Verifying po in database
        self.assertEqual(self.po.id, 1)
        self.assertEqual(self.po.items.count(), 1)
        self.assertEqual(self.po.grand_total, Decimal('129.58'))
        self.assertEqual(
            timezone('Asia/Bangkok').normalize(self.po.order_date).date(),
            datetime.datetime.now().date())
        item = self.po.items.all()[0]
        self.assertEqual(item.id, 1)
        self.assertEqual(item.quantity, 10)
        self.assertEqual(item.total, Decimal('121.1'))

        modified_po_data = copy.deepcopy(base_purchase_order)
        modified_po_data['items'][1]['unit_cost'] = Decimal('11.99')
        modified_po_data['items'][1]['comments'] = 'test change'
        modified_po_data['items'][1]['description'] = "test description change"
        del modified_po_data['items'][1]['supply']
        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po_data)

        #Verify the response
        self.assertEqual(resp.status_code, 200, msg=resp)
        po = resp.data
        self.assertEqual(po['id'], 1)
        self.assertEqual(po['supplier']['id'], 1)
        self.assertEqual(po['vat'], 7)
        #self.assertEqual(Decimal(po['grand_total']), Decimal('74.85'))
        self.assertEqual(po['discount'], 0)
        self.assertEqual(po['revision'], 1)
        self.assertEqual(len(po['items']), 2)
        #self.assertEqual(po['status'], 'PAID')
        #Check the new pdf
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(po['pdf']['url'])

        item1 = po['items'][0]
        logger.debug(item1)
        self.assertEqual(item1['id'], 2)
        self.assertEqual(item1['quantity'], Decimal('10.0000000000'))
        self.assertEqual(item1['description'], u'Pattern: Maxx, Col: Blue')
        self.assertEqual(Decimal(item1['unit_cost']), Decimal('12.1100'))
        self.assertEqual(Decimal(item1['total']), Decimal('121.10'))

        item2 = po['items'][1]
        logger.debug(item2)
        self.assertEqual(item2['id'], 3)
        self.assertEqual(item2['quantity'], Decimal('3.0000000000'))
        self.assertEqual(item2['comments'], 'test change')
        self.assertEqual(item2['description'], 'test description change')
        self.assertEqual(Decimal(item2['unit_cost']), Decimal('11.99'))
        self.assertEqual(Decimal(item2['total']), Decimal('35.97'))

        #Verify database record
        po = PurchaseOrder.objects.get(pk=1)

        self.assertEqual(po.supplier.id, 1)
        #self.assertEqual(timezone('Asia/Bangkok').normalize(po.order_date), datetime.datetime.now().date())
        self.assertEqual(po.vat, 7)
        self.assertEqual(po.grand_total, Decimal('168.06'))
        self.assertEqual(po.items.count(), 2)

        # Check new item in the database
        item2_d = po.items.all().order_by('id')[1]
        self.assertEqual(item2_d.id, 3)
        self.assertEqual(item2_d.description, 'test description change')
        self.assertEqual(item2_d.comments, 'test change')
        self.assertEqual(item2_d.quantity, 3)
        self.assertEqual(item2_d.unit_cost, Decimal('11.99'))
        self.assertEqual(item2_d.total, Decimal('35.97'))

        # Check new supply product in the database
        products = SupplyProduct.objects.filter(supply=item2_d.supply,
                                                supplier=self.po.supplier)
        self.assertEqual(products.count(), 1)
        product = products.all()[0]
        self.assertEqual(product.supply.id, item2_d.supply.id)
        self.assertEqual(product.supplier.id, self.po.supplier.id)
        self.assertEqual(product.cost, Decimal('11.99'))

    def xtest_adding_a_new_item_with_no_supply(self):
        """
            Test adding a new item to the purchase order with no previous supply or product"
            """
        print '\n'
        logger.debug('Add a new item to a current PO via PUT')
        print '\n'

        #Verifying po in database
        self.assertEqual(self.po.id, 1)
        self.assertEqual(self.po.items.count(), 1)
        self.assertEqual(self.po.grand_total, Decimal('129.58'))
        self.assertEqual(
            timezone('Asia/Bangkok').normalize(self.po.order_date).date(),
            datetime.datetime.now().date())
        item = self.po.items.all()[0]
        self.assertEqual(item.id, 1)
        self.assertEqual(item.quantity, 10)
        self.assertEqual(item.total, Decimal('121.1'))

        modified_po_data = copy.deepcopy(base_purchase_order)
        modified_po_data['items'][1]['unit_cost'] = Decimal('11.99')
        modified_po_data['items'][1]['comments'] = 'test change'
        modified_po_data['items'][1]['description'] = "test description change"
        modified_po_data['status'] = 'PROCESSED'

        logger.debug(modified_po_data)

        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po_data)

        #Verify the response
        self.assertEqual(resp.status_code, 200, msg=resp)
        po = resp.data
        self.assertEqual(po['id'], 1)
        self.assertEqual(po['supplier']['id'], 1)
        self.assertEqual(po['vat'], 7)
        #self.assertEqual(Decimal(po['grand_total']), Decimal('74.85'))
        self.assertEqual(po['discount'], 0)
        self.assertEqual(po['revision'], 1)
        self.assertEqual(len(po['items']), 2)
        #self.assertEqual(po['status'], 'PAID')
        #Check the new pdf
        #webtbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(po['pdf']['url'])

        item1 = po['items'][0]
        logger.debug(item1)
        self.assertEqual(item1['id'], 2)
        self.assertEqual(item1['quantity'], '10.0000000000')
        self.assertEqual(item1['description'], u'Pattern: Maxx, Col: Blue')
        self.assertEqual(Decimal(item1['unit_cost']), Decimal('12.1100'))
        self.assertEqual(Decimal(item1['total']), Decimal('121.10'))

        item2 = po['items'][1]
        logger.debug(item2)
        self.assertEqual(item2['id'], 3)
        self.assertEqual(item2['quantity'], '3.0000000000')
        self.assertEqual(item2['comments'], 'test change')
        self.assertEqual(item2['description'], 'test description change')
        self.assertEqual(Decimal(item2['unit_cost']), Decimal('11.99'))
        self.assertEqual(Decimal(item2['total']), Decimal('35.97'))

        #Verify database record
        po = PurchaseOrder.objects.get(pk=1)

        self.assertEqual(po.supplier.id, 1)
        self.assertEqual(po.status, 'PROCESSED')
        #self.assertEqual(timezone('Asia/Bangkok').normalize(po.order_date), datetime.datetime.now().date())
        self.assertEqual(po.vat, 7)
        self.assertEqual(po.grand_total, Decimal('168.07'))
        self.assertEqual(po.items.count(), 2)

        # Check new item in the database
        item2_d = po.items.all().order_by('id')[1]
        self.assertEqual(item2_d.id, 203)
        self.assertEqual(item2_d.description, 'test description change')
        self.assertEqual(item2_d.comments, 'test change')
        self.assertEqual(item2_d.quantity, 3)
        self.assertEqual(item2_d.unit_cost, Decimal('11.99'))
        self.assertEqual(item2_d.total, Decimal('35.97'))

        # Check new supply product in the database
        products = SupplyProduct.objects.filter(supply=item2_d.supply,
                                                supplier=self.po.supplier)
        self.assertEqual(products.count(), 1)
        product = products.all()[0]
        self.assertEqual(product.supply.id, item2_d.supply.id)
        self.assertEqual(product.supplier.id, self.po.supplier.id)
        self.assertEqual(product.cost, Decimal('11.99'))

    def test_updating_po_items(self):
        """
        Test updating properties of items in the purchase order
        
        """
        print '\n'
        logger.debug('Updating items')
        print '\n'

        modified_po_data = copy.deepcopy(base_purchase_order)
        modified_po_data['status'] = 'PROCESSED'
        modified_po_data['items'][0]['purchasing_units'] = 'set'

        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po_data)

        po = resp.data
        item1 = po['items'][0]
        #self.assertIn('purchasing_units', item1)
        #self.assertEqual(item1['purchasing_units'], 'set')

    def xtest_updating_po_with_discount(self):
        """
        """
        print '\n'
        logger.debug(
            "Update purchase order with a discount for individual supply")
        print '\n'

        #Verify the original po
        self.assertEqual(self.po.id, 1)
        self.assertEqual(self.po.items.count(), 1)
        self.assertEqual(self.po.grand_total, Decimal('129.58'))
        item = self.po.items.all()[0]
        self.assertEqual(item.id, 1)
        self.assertEqual(item.quantity, 10)
        self.assertEqual(item.total, Decimal('121.1'))

        modified_po = copy.deepcopy(base_purchase_order)
        modified_po['items'][0]['discount'] = 50
        modified_po['items'][0]['id'] = 1
        modified_po['status'] = 'PROCESSED'
        self.assertEqual(len(modified_po['items']), 2)

        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po)
        self.assertEqual(resp.status_code, 200, msg=resp)
        resp_obj = resp.data
        self.assertEqual(resp_obj['revision'], 1)
        #Check the new pdf
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(resp_obj['pdf']['url'])

        item1 = resp_obj['items'][0]
        item2 = resp_obj['items'][1]
        self.assertEqual(item1['id'], 1)
        self.assertEqual(item1['quantity'], Decimal('10.0000000000'))
        self.assertEqual(Decimal(item1['unit_cost']), Decimal('12.11'))
        self.assertEqual(Decimal(item1['total']), Decimal('60.55'))
        self.assertEqual(item2['id'], 2)
        self.assertEqual(item2['quantity'], Decimal('3.0000000000'))
        self.assertEqual(item2['discount'], 5)
        self.assertEqual(Decimal(item2['unit_cost']), Decimal('12.11'))
        self.assertEqual(Decimal(item2['total']), Decimal('34.51'))
        self.assertEqual(Decimal(resp_obj['grand_total']), Decimal('101.72'))

        po = PurchaseOrder.objects.get(pk=1)
        item1 = po.items.order_by('id').all()[0]
        self.assertEqual(item1.id, 1)
        self.assertEqual(item1.quantity, Decimal('10.00'))
        self.assertEqual(item1.discount, 50)
        self.assertEqual(item1.unit_cost, Decimal('12.11'))
        self.assertEqual(item1.total, Decimal('60.55'))
        item2 = po.items.order_by('id').all()[1]
        self.assertEqual(item2.id, 2)
        self.assertEqual(item2.quantity, Decimal('3.00'))
        self.assertEqual(item2.unit_cost, Decimal('12.11'))
        self.assertEqual(item2.discount, 5)
        self.assertEqual(item2.total, Decimal('34.51'))

    def test_updating_po_with_new_currency(self):
        """
        Test updating the status of supplies and automatically checking in supplies 
        """
        #test original quantity

        modified_po = copy.deepcopy(base_purchase_order)
        modified_po['currency'] = 'RMB'

        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po)

        self.assertEqual(resp.status_code, 200, msg=resp)

        po = resp.data

        self.assertEqual(po['currency'], 'RMB')

    def test_updating_the_supply_price(self):
        """
        Test updating a po with a new cost for an item
        """
        self.assertEqual(self.po.id, 1)
        self.assertEqual(self.po.items.count(), 1)
        item = self.po.items.all()[0]
        self.assertEqual(item.id, 1)
        self.assertEqual(item.unit_cost, Decimal('12.11'))
        self.assertEqual(Log.objects.all().count(), 0)

        modified_po = copy.deepcopy(base_purchase_order)
        modified_po['items'][0]['unit_cost'] = Decimal('10.05')
        modified_po['items'][0]['id'] = 1
        modified_po['status'] = 'PROCESSED'
        del modified_po['items'][1]
        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po)
        self.assertEqual(resp.status_code, 200, msg=resp)
        resp_obj = resp.data
        self.assertEqual(resp_obj['revision'], 1)
        #Check the new pdf
        #webbrowser.get("open -a /Applications/Google\ Chrome.app %s").open(resp_obj['pdf']['url'])

        self.assertEqual(resp_obj['id'], 1)
        self.assertEqual(resp_obj['supplier']['id'], 1)
        self.assertEqual(resp_obj['vat'], 7)
        self.assertEqual(resp_obj['discount'], 0)
        self.assertEqual(resp_obj['revision'], 1)
        self.assertEqual(Decimal(resp_obj['grand_total']), Decimal('107.54'))
        self.assertEqual(len(resp_obj['items']), 1)
        item1 = resp_obj['items'][0]
        self.assertEqual(item1['id'], 1)
        self.assertEqual(item1['quantity'], Decimal('10.0000000000'))
        self.assertEqual(Decimal(item1['unit_cost']), Decimal('10.05'))
        self.assertEqual(Decimal(item1['total']), Decimal('100.50'))

        #Confirm cost change for item and supply in the database
        po = PurchaseOrder.objects.get(pk=1)
        self.assertEqual(po.grand_total, Decimal('107.54'))
        item1 = po.items.order_by('id').all()[0]
        self.assertEqual(item1.id, 1)
        self.assertEqual(item1.quantity, 10)
        self.assertEqual(item1.unit_cost, Decimal('10.05'))
        supply = item1.supply
        supply.supplier = po.supplier
        self.assertEqual(supply.cost, Decimal('10.05'))

        self.assertEqual(Log.objects.all().count(), 1)
        log = Log.objects.all()[0]
        self.assertEqual(log.cost, Decimal('10.05'))
        self.assertEqual(log.supply, supply)
        self.assertEqual(log.supplier, po.supplier)
        self.assertEqual(
            log.message,
            "Price change from 12.11USD to 10.05USD for Pattern: Maxx, Col: Blue [Supplier: Zipper World]"
        )

        # Confirm that there is still only one product for this supply and supplier
        # in the database
        products = Product.objects.filter(supply=supply, supplier=po.supplier)
        self.assertEqual(len(products), 1)

    def test_updating_item_status(self):
        """
        Test updating the status of supplies and automatically checking in supplies 
        """
        #test original quantity
        self.assertEqual(self.supply1.quantity, 10)
        self.assertEqual(self.supply2.quantity, 10)

        modified_po = copy.deepcopy(base_purchase_order)
        modified_po['status'] = 'Received'
        modified_po['items'][0]['id'] = 1
        modified_po['items'][0]['status'] = 'Receieved'

        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po)

        self.assertEqual(resp.status_code, 200, msg=resp)

        po = resp.data

        self.assertEqual(Supply.objects.get(pk=1).quantity, 20)

    def test_updating_the_project(self):
        """
        Tests updating the project, phase, and room of a purchase order
        """
        modified_po = copy.deepcopy(base_purchase_order)

    def test_updating_to_receive_items(self):
        """
        Test updating the status of the po in order to to receive it
        
        When a purchase order is received, the items received should automatically be added to the 
        supply inventory quantity
        """
        modified_po = copy.deepcopy(base_purchase_order)
        del modified_po['items'][1]
        modified_po['items'][0]['id'] = 1
        modified_po['items'][0]['status'] = 'RECEIVED'
        modified_po['status'] = 'RECEIVED'
        self.assertEqual(Supply.objects.get(pk=1).quantity, 10)

        resp = self.client.put('/api/v1/purchase-order/1/',
                               format='json',
                               data=modified_po)

        self.assertEqual(resp.status_code, 200, msg=resp)

        po_data = resp.data
        self.assertEqual(po_data['id'], 1)
        self.assertEqual(po_data['status'], 'RECEIVED')

        item1 = po_data['items'][0]
        self.assertEqual(item1['id'], 1)
        self.assertEqual(item1['status'], 'RECEIVED')

        #Test database values
        po = PurchaseOrder.objects.get(pk=1)
        self.assertEqual(po.id, 1)
        self.assertEqual(po.status, 'RECEIVED')
        for item in po.items.all():
            self.assertEqual(item.status, "RECEIVED")

        supply = Supply.objects.get(pk=1)
        self.assertEqual(supply.quantity, 20)
        log = Log.objects.all().order_by('-id')[0]
        self.assertEqual(log.action, "ADD")
        self.assertEqual(log.quantity, 10)
        self.assertEqual(log.supplier.id, 1)
        self.assertEqual(
            log.message,
            "Received 10m of Pattern: Maxx, Col: Blue from Zipper World")

    def test_multiple_creates_do_not_increase_products(self):
        """
        Test multiple creates
        
        When a purchase order is received, the items received should automatically be added to the 
        supply inventory quantity
        """
        for i in xrange(0, 10):
            modified_po = copy.deepcopy(base_purchase_order)
            self.assertEqual(Supply.objects.get(pk=1).quantity, 10)

            resp = self.client.post('/api/v1/purchase-order/',
                                    format='json',
                                    data=modified_po)

            self.assertEqual(resp.status_code, 201, msg=resp)

            po_data = resp.data
            self.assertEqual(po_data['status'], 'AWAITING APPROVAL')

            item1 = po_data['items'][0]
            #self.assertEqual(item1['supply']['id'], 1)
            self.assertEqual(item1['status'], u'Ordered')

            item2 = po_data['items'][1]
            #self.assertEqual(item1['supply']['id'], 2)
            self.assertEqual(item1['status'], u'Ordered')

            #Test database values
            po = PurchaseOrder.objects.get(pk=resp.data['id'])
            self.assertEqual(po.status, 'AWAITING APPROVAL')
            for item in po.items.all():
                self.assertEqual(item.status, u"Ordered")

            supplier = Supplier.objects.get(pk=1)

            supply = Supply.objects.get(pk=1)
            self.assertEqual(supply.quantity, 10)
            self.assertEqual(
                supply.products.filter(supplier=supplier).count(), 1)

            supply = Supply.objects.get(pk=2)
            self.assertEqual(supply.quantity, 10)
            self.assertEqual(
                supply.products.filter(supplier=supplier).count(), 1)
Exemplo n.º 23
0
 fabric.grade = f['grade']
 fabric.repeat = f['repeat']
 fabric.units = 'yd'
 fabric.type = 'fabric'
 fabric.save()
 
 filename = "{0} Col: {1}".format(fabric.pattern, fabric.color)
 fabric.description = filename
 fabric.save()
 
 print fabric.id, fabric.description
 
 try:
     product = Product.objects.get(supply=fabric, supplier=supplier)
 except Product.DoesNotExist:
     product = Product(supply=fabric, supplier=supplier)
     
 product.purchasing_units = 'yd'
 try:
     product.cost = Decimal(fabric.grade) * Decimal('1.10')
 except Exception:
     product.cost = 0
     
 product.save()
 
 if 'image' in f:
     f['image'].save(filename + ".jpg")
     image = S3Object.create(filename + ".jpg", 
                             "supply/image/{0}-{1}.jpg".format(fabric.pattern, fabric.color),
                             'media.dellarobbiathailand.com')
     fabric.image = image
Exemplo n.º 24
0
    def setUp(self):
        """
        Set up dependent objects
        """
        super(PurchaseOrderTest, self).setUp()

        self.ct = ContentType(app_label="po")
        self.ct.save()
        self.p = Permission(codename="add_purchaseorder", content_type=self.ct)
        self.p.save()
        self.p2 = Permission(codename="change_purchaseorder",
                             content_type=self.ct)
        self.p2.save()
        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(
            self.username, '*****@*****.**', self.password)
        self.user.save()
        self.user.user_permissions.add(self.p)
        self.user.user_permissions.add(self.p2)
        self.client.login(username=self.username, password=self.password)
        self.client.force_authenticate(self.user)

        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(**base_address)
        self.address.contact = self.supplier
        self.address.save()
        self.contact = SupplierContact(name='test',
                                       email='*****@*****.**',
                                       telephone=1234,
                                       primary=True)
        self.contact.supplier = self.supplier
        self.contact.save()

        # Create Custom Supply
        # not implemented

        # Create Fabric
        self.supply = Fabric.create(**base_fabric)

        #self.supply.units = "m^2"
        self.supply.save()
        self.supply1 = self.supply

        self.product = Product(supply=self.supply,
                               supplier=self.supplier,
                               cost=base_fabric['unit_cost'],
                               purchasing_units='m')
        self.product.save()
        self.supply2 = Fabric.create(**base_fabric2)
        self.supply2.discount = 5
        self.supply2.save()
        self.product2 = Product(supply=self.supply2,
                                supplier=self.supplier,
                                cost=base_fabric['unit_cost'])
        self.product2.save()
        self.supply1.supplier = self.supplier
        self.supply2.supplier = self.supplier

        #Create supply with no target item
        self.supply3 = Supply.objects.create(description='test supply')
        self.supply3.id = 203
        self.supply3.save()

        #Create a project
        self.project = Project()
        self.project.codename = 'MC House'
        self.project.save()

        self.po = PurchaseOrder()
        self.po.employee = self.user
        self.po.supplier = self.supplier
        self.po.terms = self.supplier.terms
        self.po.vat = 7
        self.order_date = datetime.datetime(2017,
                                            1,
                                            15,
                                            15,
                                            30,
                                            0,
                                            0,
                                            tzinfo=timezone('Asia/Bangkok'))
        self.po.order_date = self.order_date
        self.po.receive_date = datetime.datetime.now()
        self.po.save()
        #self.po.create_and_upload_pdf()

        self.item = Item.create(supplier=self.supplier,
                                id=1,
                                **base_purchase_order['items'][0])
        self.item.purchase_order = self.po
        self.item.save()

        self.po.calculate_total()
        self.po.save()
Exemplo n.º 25
0
 def setUp(self):
     """
     Set up dependent objects
     """
     super(PurchaseOrderTest, self).setUp()
     
     self.ct = ContentType(app_label="po")
     self.ct.save()
     self.p = Permission(codename="add_purchaseorder", content_type=self.ct)
     self.p.save()
     self.p2 = Permission(codename="change_purchaseorder", content_type=self.ct)
     self.p2.save()
     #Create the user
     self.username = '******'
     self.password = '******'
     self.user = User.objects.create_user(self.username, '*****@*****.**', self.password)
     self.user.save()
     self.user.user_permissions.add(self.p)
     self.user.user_permissions.add(self.p2)
     self.client.login(username=self.username, password=self.password)
     
     
     self.supplier = Supplier(**base_supplier)
     self.supplier.save()
     self.address = Address(**base_address)
     self.address.contact = self.supplier
     self.address.save()
     self.contact = SupplierContact(name='test', email='*****@*****.**', telephone=1234, primary=True)
     self.contact.supplier = self.supplier
     self.contact.save()
     self.supply = Fabric.create(**base_fabric)
    
     #self.supply.units = "m^2"
     self.supply.save()
     self.supply1 = self.supply
     
     self.product = Product(supply=self.supply, supplier=self.supplier, cost=base_fabric['unit_cost'],
                            purchasing_units='m')
     self.product.save()
     self.supply2 = Fabric.create(**base_fabric2)
     self.supply2.discount = 5
     self.supply2.save()
     self.product2 = Product(supply=self.supply2, supplier=self.supplier, cost=base_fabric['unit_cost'])
     self.product2.save()
     self.supply.supplier = self.supplier
     self.supply2.supplier = self.supplier
     
     #Create a project
     self.project = Project()
     self.project.codename = 'MC House'
     self.project.save()
     
     self.po = PurchaseOrder()
     self.po.employee = self.user
     self.po.supplier = self.supplier
     self.po.terms = self.supplier.terms
     self.po.vat = 7
     self.po.order_date = datetime.datetime(2014, 3, 2)
     self.po.save()
     #self.po.create_and_upload_pdf()
     
     self.item = Item.create(supplier=self.supplier, id=1, **base_purchase_order['items'][0])
     self.item.purchase_order = self.po
     self.item.save()
     
     self.po.calculate_total()
     self.po.save()
Exemplo n.º 26
0
class FabricAPITestCase(APITestCase):
    
    def setUp(self):
        """
        Set up the view 
        
        -login the user
        """
        super(FabricAPITestCase, self).setUp()
        
        self.create_user()
        self.client.login(username='******', password='******')
        
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.supply = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)
        self.supply2 = Fabric.create(**base_fabric)
        self.assertIsNotNone(self.supply.pk)
        
        self.product = Product(supplier=self.supplier, supply=self.supply)
        self.product.save()
    
    def create_user(self):
        self.user = User.objects.create_user('test', '*****@*****.**', 'test')
        self.ct = ContentType(app_label='supplies')
        self.ct.save()
        self._create_and_add_permission('view_cost', self.user)
        self._create_and_add_permission('change_fabric', self.user)
        self._create_and_add_permission('add_fabric', self.user)
        self._create_and_add_permission('add_quantity', self.user)
        self._create_and_add_permission('subtract_quantity', self.user)
        
    def _create_and_add_permission(self, codename, user):
        p = Permission(content_type=self.ct, codename=codename)
        p.save()
        user.user_permissions.add(p)
        
    def _remove_permission(self, codename):
        self.user.user_permissions.remove(Permission.objects.get(codename=codename, content_type=self.ct))
        
    def test_get_list(self):
        """
        Tests that a standard get call works.
        """
        
        #Testing standard GET
        resp = self.client.get('/api/v1/fabric/')
        self.assertEqual(resp.status_code, 200)
        
        #Tests the returned data
        resp_obj = resp.data
        self.assertIn('results', resp_obj)
        self.assertEqual(len(resp_obj['results']), 2)
    
    def test_get(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        resp = self.client.get('/api/v1/fabric/1/')
        self.assertEqual(resp.status_code, 200)
        
        obj = resp.data
        #self.assertEqual(float(obj['cost']), float('100'))
        
    def test_get_without_price(self):
        """
        Tests getting a supply that doesn't have the price 
        where the user is not authorized to view the price
        """
        #Delete the view cost permission from the user
        self.user.user_permissions.remove(Permission.objects.get(codename='view_cost', content_type=self.ct))
        
        #tests the response
        resp = self.client.get('/api/v1/fabric/1/')
        self.assertEqual(resp.status_code, 200)
        
        #Tests the data returned
        obj = resp.data
        self.assertNotIn("cost", obj)
        
    def test_post(self):
        """
        Tests posting to the server
        """
        #Test creating an objects. 
        self.assertEqual(Supply.objects.count(), 2)
        resp = self.client.post('/api/v1/fabric/', format='json',
                                    data=base_fabric)
        self.assertEqual(resp.status_code, 201, msg=resp)
       
        #Tests the dat aturned
        obj = resp.data
        self.assertEqual(obj['id'], 3)
        self.assertEqual(obj['width'], '100.00')
        self.assertEqual(obj['depth'], '0.00')
        self.assertEqual(obj['height'], '300.00')
        self.assertEqual(obj['description'], u'Max Col: Hot Pink')
        self.assertNotIn('reference', obj)
        self.assertNotIn('cost', obj)
        self.assertIn('suppliers', obj)
        
        supplier = obj['suppliers'][0]
        self.assertEqual(supplier['reference'], 'A2234')
        self.assertEqual(int(supplier['cost']), 100)
        
    def test_put(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['cost'] = '111'
        modified_data['color'] = 'Aqua'
        modified_data['pattern'] = 'Stripes'
        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 2)
        resp = self.client.put('/api/v1/fabric/1/', format='json',
                                   data=modified_data)
        
        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 2)

        #Tests the returned data
        obj = resp.data
        self.assertEqual(obj['color'], 'Aqua')
        self.assertEqual(obj['pattern'], 'Stripes')
        
    def test_put_add_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['quantity'] = '14'
        modified_data['color'] = 'Aqua'
        modified_data['pattern'] = 'Stripes'

        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.put('/api/v1/fabric/1/', format='json',
                                   data=modified_data)
        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('14'))

        #Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('14'))
        
    def test_put_subtract_quantity(self):
        """
        Tests adding quantity to the item
        """
        modified_data = base_supply.copy()
        modified_data['quantity'] = '8'
        modified_data['color'] = 'Aqua'
        modified_data['pattern'] = 'Stripes'

        #Tests the api and the response
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('10.8'))
        resp = self.client.put('/api/v1/fabric/1/', format='json',
                                   data=modified_data)
        
        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Supply.objects.count(), 2)
        self.assertEqual(Supply.objects.get(pk=1).quantity, float('8'))

        #Tests the returned data
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('8'))
      
    @unittest.skip('ok')  
    def test_put_add_quantity_fail(self):
        """
        Tests an unauthorized addition of quantity
        """
        #Delete permissions
        self._remove_permission("add_quantity")
        
        #Create new data
        modified_data = base_fabric.copy()
        modified_data['quantity'] = '20'
        
        #Tests the api and response
        resp = self.client.put('/api/v1/fabric/1/', format='json',
                                   data=modified_data)
        self.assertEqual(Fabric.objects.get(pk=1).quantity, float('10.8'))
        #Tests the data retured
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('10.8'))
        
    @unittest.skip('ok')
    def test_put_subtract_quantity_fail(self):
        """
        Tests an unauthorized addition of quantity
        """
        #Delete permissions
        self._remove_permission("subtract_quantity")
        
        #Create new data
        modified_data = base_fabric.copy()
        modified_data['quantity'] = '6'
        
        #Tests the api and response
        resp = self.client.put('/api/v1/fabric/1/', format='json',
                                   data=modified_data)
        self.assertEqual(Fabric.objects.get(pk=1).quantity, float('10.8'))
        #Tests the data retured
        obj = resp.data
        self.assertEqual(float(obj['quantity']), float('10.8'))