Esempio n. 1
0
    def setUp(self):
        """
        Set up the environment for the test cases
        """
        super(GroupResourceTest, self).setUp()
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_superuser('tester',
                                                  '*****@*****.**', 'test')
        self.user.user_permissions.add(
            Permission.objects.get(codename="add_user"))
        self.api_client.client.login(username='******', password='******')

        #Create a group
        self.group = Group(name="God")
        self.group.save()

        #Create a permission
        self.ct = ContentType(name='test')
        self.ct.save()
        self.permission = Permission(name='Test',
                                     codename='test',
                                     content_type=self.ct)
        self.permission.save()

        self.group.permissions.add(self.permission)
Esempio n. 2
0
 def mutate_and_get_payload(cls, root, info, **kwargs):
     app_labe = kwargs.get('app_label')
     model = kwargs.get('models')
     content_type = ContentType(app_labe=app_labe,
                                model=model)
     content_type.save()
     return CreateContentType(content_type=content_type)
Esempio n. 3
0
 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)
Esempio n. 4
0
    def setUp(self):
        """
        Set up dependent objects
        """
        super(ItemTest, 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.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.item = Item(unit_cost=Decimal('13.55'),
                         quantity=Decimal('10'),
                         supply=self.supply)
        self.item.description = self.supply.description
        self.item.purchase_order = self.po
        self.item.save()
Esempio n. 5
0
 def create_user(self):
     self.user = User.objects.create_user('test', '*****@*****.**', 'test')
     self.ct = ContentType(app_label='acknowledgements')
     self.ct.save()
     perm = Permission(content_type=self.ct, codename='change_item')
     perm.save()
     self.user.user_permissions.add(perm)
     perm = Permission(content_type=self.ct, codename='change_fabric')
     perm.save()
     self.user.user_permissions.add(perm)
     self.assertTrue(self.user.has_perm('acknowledgements.change_item'))
     return self.user
Esempio n. 6
0
    def test_put_change_groups(self):
        """
        Tests adding a group to a user
        """
        #Create groups to be added
        group1 = Group(name="Testing")
        group1.save()

        #Create group to be removed
        group2 = Group(name='Bye')
        group2.save()
        self.user.groups.add(group2)

        #Create a permission
        ct = ContentType(name='test')
        ct.save()
        perm = Permission(codename='test', name='test', content_type=ct)
        perm.save()
        group1.permissions.add(perm)
        perm = Permission(codename='removed', name='removed', content_type=ct)
        perm.save()
        group2.permissions.add(perm)

        #Check that user has group to be removed and the permissions of that group
        self.assertEqual(self.user.groups.count(), 1)
        self.assertEqual(self.user.groups.all()[0].name, 'Bye')

        #Test the api and response
        resp = self.client.put('/api/v1/user/1/',
                               format='json',
                               data={
                                   'username': '******',
                                   'email': '*****@*****.**',
                                   'first_name': 'Charlie',
                                   'last_name': 'P',
                                   'groups': [{
                                       'id': 1,
                                       'name': 'Testing'
                                   }]
                               })
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(self.user.groups.count(), 1)
        self.assertEqual(self.user.groups.all()[0].name, 'Testing')

        #Tests the returned data
        user = resp.data
        self.assertEqual(len(user['groups']), 1)
        self.assertIn('id', user['groups'][0])
        self.assertIn('name', user['groups'][0])
    def _create_client(self):
        # create user and login
        username = '******'
        password = '******'
        hash_password = '******'

        cursor = connection.cursor()
        cursor.execute(
            'INSERT INTO auth_user SET password=%s, is_superuser=%s, username=%s,'
            ' email=%s, is_active=%s, is_staff=%s, first_name=%s, last_name=%s',
            [hash_password, 1, username, username, 1, 1, 'test', 'test'])
        cursor.close()

        user = User.objects.get(username=username)

        REGISTRY['user'] = user

        UserProfile.objects.create(user=user)
        user.profile.trading_desk.add(
            TradingDesk.objects.create(trading_desk='trading_desk'))

        group = Group(name='Ad Manager Admin')
        group.save()

        user.groups.add(group)

        content_type = ContentType(name='ad manager',
                                   app_label='dashboard',
                                   model='admanager')
        content_type.save()

        permission = Permission(name='Ad Manager Admin',
                                content_type=content_type,
                                codename='am_admin')
        permission.save()

        group.permissions.add(permission)

        # pylint: disable=no-member
        self.user = user

        client = Client()
        client.login(username=user.username, password=password)
        self.logged_in_client = client
        return user
Esempio n. 8
0
 def test_put_change_groups(self):
     """
     Tests adding a group to a user
     """
     #Create groups to be added
     group1 = Group(name="Testing")
     group1.save()
     
     #Create group to be removed
     group2 = Group(name='Bye')
     group2.save()
     self.user.groups.add(group2)
     
     #Create a permission
     ct = ContentType(name='test')
     ct.save()
     perm = Permission(codename='test', name='test',
                       content_type=ct)
     perm.save()
     group1.permissions.add(perm)
     perm = Permission(codename='removed', name='removed',
                       content_type=ct)
     perm.save()
     group2.permissions.add(perm)
     
     #Check that user has group to be removed and the permissions of that group
     self.assertEqual(self.user.groups.count(), 1)
     self.assertEqual(self.user.groups.all()[0].name, 'Bye')
     
     #Test the api and response
     resp = self.client.put('/api/v1/user/1/', format='json',
                                data={'username':'******',
                                      'email': '*****@*****.**',
                                      'first_name': 'Charlie',
                                      'last_name': 'P',
                                      'groups': [{'id': 1, 'name': 'Testing'}]})
     self.assertEqual(resp.status_code, 200)
     self.assertEqual(self.user.groups.count(), 1)
     self.assertEqual(self.user.groups.all()[0].name, 'Testing')
     
     #Tests the returned data
     user = resp.data
     self.assertEqual(len(user['groups']), 1)
     self.assertIn('id', user['groups'][0])
     self.assertIn('name', user['groups'][0])
Esempio n. 9
0
 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)
Esempio n. 10
0
 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)
Esempio n. 11
0
 def create_user(self):
     self.user = User.objects.create_user('test', '*****@*****.**', 'test')
     self.ct = ContentType(app_label='acknowledgements')
     self.ct.save()
     perm = Permission(content_type=self.ct, codename='change_item')
     perm.save()
     self.user.user_permissions.add(perm)
     perm = Permission(content_type=self.ct, codename='change_fabric')
     perm.save()
     self.user.user_permissions.add(perm)
     self.assertTrue(self.user.has_perm('acknowledgements.change_item'))
     return self.user
Esempio n. 12
0
 def setUp(self):
     """
     Set up dependent objects
     """
     super(ItemTest, 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.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.item = Item(unit_cost=Decimal('13.55'), quantity=Decimal('10'), supply=self.supply)
     self.item.description = self.supply.description
     self.item.purchase_order = self.po
     self.item.save()
Esempio n. 13
0
 def setUp(self):
     """
     Set up the environment for the test cases
     """
     super(GroupResourceTest, self).setUp()
     self.username = '******'
     self.password = '******'
     self.user = User.objects.create_superuser('tester', '*****@*****.**', 'test')
     self.user.user_permissions.add(Permission.objects.get(codename="add_user"))
     self.api_client.client.login(username='******', password='******')
     
     #Create a group
     self.group = Group(name="God")
     self.group.save()
     
     #Create a permission
     self.ct = ContentType(name='test')
     self.ct.save()
     self.permission = Permission(name='Test', codename='test',
                                  content_type=self.ct)
     self.permission.save()
     
     self.group.permissions.add(self.permission)
Esempio n. 14
0
 def create_user(self):
     self.user = User.objects.create_user('test', '*****@*****.**', 'test')
     self.ct = ContentType(app_label='projects')
     self.ct.save()
     #self._create_and_add_permission('view_cost', self.user)
     self._create_and_add_permission('change_project', self.user)
Esempio n. 15
0
class ProjectResourceTestCase(APITestCase):
    def setUp(self):
        """
        Sets up for tests
        """
        super(ProjectResourceTestCase, self).setUp()
        
        self.create_user()
        #self.api_client.client.login(username='******', password='******')
        
        #self.customer = Customer.create(**base_customer)
        #self.project = Project.create(**base_project)
        self.project = Project(codename="Ladawan")
        self.project.save()
        self.supply = Supply(description='Grommet')
        self.supply.save()
        self.supply2 = Supply(description='Hinge')
        self.supply2.save()
        self.project_supply = ProjectSupply(supply=self.supply,
                                            project=self.project,
                                            quantity=2)
        self.project_supply.save()
    
    def create_user(self):
        self.user = User.objects.create_user('test', '*****@*****.**', 'test')
        self.ct = ContentType(app_label='projects')
        self.ct.save()
        #self._create_and_add_permission('view_cost', self.user)
        self._create_and_add_permission('change_project', 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(self):
        """
        Test retrieving resources via GET
        """
        resp = self.api_client.get('/api/v1/project')
        
        self.assertHttpOK(resp)
        obj = self.deserialize(resp)
        self.assertEqual(len(obj['objects']), 1)
        project = obj['objects'][0]
        self.assertEqual(project['id'], 1)
        self.assertEqual(project['codename'], 'Ladawan')
        
    def test_get_obj(self):
        """
        Tests retrieving a single object via GET
        """
        resp = self.api_client.get('/api/v1/project/1')
        
        self.assertHttpOK(resp)
        
        obj = self.deserialize(resp)
        self.assertEqual(obj['id'], 1)
        self.assertEqual(obj['codename'], 'Ladawan')
        self.assertIn('supplies', obj)
        self.assertEqual(len(obj['supplies']), 1)
        supply = obj['supplies'][0]
        self.assertEqual(supply['id'], 1)
        self.assertEqual(supply['description'], 'Grommet')
        self.assertEqual(int(supply['quantity']), 2)
        
    def test_get_all_projects(self):
        """
        Test retrieving full list of projects over 100"""
        for i in xrange(0, 100):
            project = Project(codename=i)
            project.save()

        self.assertEqual(Project.objects.all().count(), 101)
        
        resp = self.client.get('/api/v1/project/?page_size=99999', format='json')
        
        self.assertEqual(resp.status_code, 200)

        data = resp.data['results']
        self.assertEqual(len(data), 101)
        
    @unittest.skip('')
    def test_create_project(self):
        """
        Tests creating a project
        """
        self.assertIsNotNone(self.project)
        self.assertIsInstance(self.project, Project)
        self.assertIsInstance(self.project.customer, Customer)
        self.assertEqual(self.project.customer, self.customer)
        self.assertEqual(self.project.reference, "S5")
        self.assertEqual(self.project.type, "Condominium")
        self.assertEqual(self.project.due_date, base_due_date.date())
        self.assertEqual(self.project.codename, "Haze")

    def test_update_project(self):
        """
        Tests updating a project
        """
        data = {'codename': "Ladawan 329",
                'supplies': [{'id': 1,
                              'description': 'Grommet',
                              'quantity': 5},
                              {'id': 2,
                               'quantity': 10}]}
        
        resp = self.api_client.put('/api/v1/project/1', 
                                   format='json',
                                   data=data)
        self.assertHttpOK(resp)
        
        obj = self.deserialize(resp)
        self.assertEqual(obj['id'], 1)
        self.assertEqual(obj['codename'], "Ladawan 329")
        self.assertEqual(len(obj['supplies']), 2)
        
        supply1 = obj['supplies'][0]
        self.assertEqual(supply1['id'], 1)
        self.assertEqual(supply1['description'], 'Grommet')
        self.assertEqual(int(supply1['quantity']), 5)
        
        supply2 = obj['supplies'][1]
        self.assertEqual(supply2['id'], 2)
        self.assertEqual(supply2['description'], 'Hinge')
        self.assertEqual(int(supply2['quantity']), 10)

    def test_update_project_deleting_supply(self):
        """
        Tests deleting a project supply via PUT
        """
        data = {'codename': "Ladawan 329",
                'supplies': [{'id': 2,
                              'description': 'Hinge',
                              'quantity': 10}]}   
                    
        resp = self.api_client.put('/api/v1/project/1', 
                                   format='json',
                                   data=data)
        self.assertHttpOK(resp)
        
        obj = self.deserialize(resp)
        self.assertEqual(obj['id'], 1)
        self.assertEqual(obj['codename'], "Ladawan 329")
        self.assertEqual(len(obj['supplies']), 1)
        
        supply1 = obj['supplies'][0]
        self.assertEqual(supply1['id'], 2)
        self.assertEqual(supply1['description'], 'Hinge')
        self.assertEqual(int(supply1['quantity']), 10)
      
        
    @unittest.skip('')
    def _update_due_date(self):
        """
        Tests the updating of the due date
        """
        due_date = dateutil.parser.parse("2013-04-26T13:59:01.143Z")
        self.project.update(due_date=due_date.isoformat())
        self.assertEqual(self.project.due_date, due_date.date())
        delta = datetime.timedelta(days=5)
        due_date2 = due_date + delta
        self.project.update(due_date=due_date2)
        self.assertEqual(self.project.due_date, due_date2.date())
Esempio n. 16
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()
Esempio n. 17
0
class ItemTest(TestCase):
    """
    Tests the PO Item
    """
    def setUp(self):
        """
        Set up dependent objects
        """
        super(ItemTest, 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.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.item = Item(unit_cost=Decimal('13.55'), quantity=Decimal('10'), supply=self.supply)
        self.item.description = self.supply.description
        self.item.purchase_order = self.po
        self.item.save()

    def test_creating_item_with_no_product_with_unit_cost(self):
        """Test creating a item via the serializer where there is no product
        """
        context = {'po': self.po,
                   'supplier': self.supplier}
        data = {'supply': self.supply.id,
                'unit_cost': 10,
                'quantity': 5,
                'units': 'yd'}
                
        item_serializer = ItemSerializer(context=context, data=data)
        if item_serializer.is_valid(raise_exception=True):
            item_serializer.save()
            
        # Verify product is created
        self.assertEqual(Product.objects.filter(supply=self.supply, supplier=self.supplier).count(), 1)
        
        # Verify item
        resp_data = item_serializer.data
        
        self.assertEqual(resp_data['description'], 'Pattern: Maxx, Col: Blue')
        self.assertEqual(resp_data['units'], 'yd')
        self.assertEqual(Decimal(resp_data['quantity']), Decimal('5'))
        self.assertEqual(Decimal(resp_data['total']), Decimal('50'))
        
    def test_creating_item_with_product_with_no_unit_cost(self):
        """Test creating a item via the serializer where there is no product
        """
        Product.objects.create(supply=self.supply, supplier=self.supplier, cost=Decimal('12.11'), 
                               purchasing_units="yd")
        
        context = {'po': self.po,
                   'supplier': self.supplier}
        data = {'supply': self.supply.id,
                'quantity': 5,
                'units': 'yd'}
                
        item_serializer = ItemSerializer(context=context, data=data)
        if item_serializer.is_valid(raise_exception=True):
            item_serializer.save()
            
        # Verify product is created
        self.assertEqual(Product.objects.filter(supply=self.supply, supplier=self.supplier).count(), 1)
        
        # Verify item
        resp_data = item_serializer.data
        
        self.assertEqual(resp_data['description'], 'Pattern: Maxx, Col: Blue')
        self.assertEqual(resp_data['units'], 'yd')
        self.assertEqual(Decimal(resp_data['quantity']), Decimal('5'))
        self.assertEqual(Decimal(resp_data['total']), Decimal('60.55'))
        
    def test_updating_item_without_product(self):
        
        context = {'po': self.po,
                   'supplier': self.supplier}
        data = {'supply': self.supply.id,
                'unit_cost': Decimal('11.22'),
                'quantity': 4,
                'units': 'yd'}
        
        # Verify there is no product
        self.assertEqual(Product.objects.filter(supply=self.supply, supplier=self.supplier).count(), 0)
        
        # Update item
        item_serializer = ItemSerializer(self.item, context=context, data=data)
        if item_serializer.is_valid(raise_exception=True):
            item_serializer.save()
            
        # Verify product is created
        self.assertEqual(Product.objects.filter(supply=self.supply, supplier=self.supplier).count(), 1)
        
        # Verify item
        resp_data = item_serializer.data
        
        self.assertEqual(resp_data['description'], 'Pattern: Maxx, Col: Blue')
        self.assertEqual(resp_data['units'], 'yd')
        self.assertEqual(Decimal(resp_data['quantity']), Decimal('4'))
        self.assertEqual(Decimal(resp_data['total']), Decimal('44.88'))
        
    def test_updating_item_with_product(self):
        Product.objects.create(supply=self.supply, supplier=self.supplier, cost=Decimal('12.11'), 
                               purchasing_units="yd")
                               
        context = {'po': self.po,
                   'supplier': self.supplier}
        data = {'supply': self.supply.id,
                'unit_cost': Decimal('11.22'),
                'quantity': 4,
                'units': 'm'}
        
        # Verify there is a product
        products = Product.objects.filter(supply=self.supply, supplier=self.supplier)
        self.assertEqual(products.count(), 1)
        self.assertEqual(products[0].cost, Decimal('12.11'))
        self.assertEqual(products[0].purchasing_units, 'yd')
        
        # Update item
        item_serializer = ItemSerializer(self.item, context=context, data=data)
        if item_serializer.is_valid(raise_exception=True):
            item_serializer.save()
            
        # Verify product is created
        products2 = Product.objects.filter(supply=self.supply, supplier=self.supplier)
        self.assertEqual(products2.count(), 1)
        self.assertEqual(products2[0].cost, Decimal('11.22'))
        self.assertEqual(products2[0].purchasing_units, 'm')

        # Verify item
        resp_data = item_serializer.data
        
        self.assertEqual(resp_data['description'], 'Pattern: Maxx, Col: Blue')
        self.assertEqual(resp_data['units'], 'm')
        self.assertEqual(Decimal(resp_data['quantity']), Decimal('4'))
        self.assertEqual(Decimal(resp_data['total']), Decimal('44.88'))
Esempio n. 18
0
class ShippingResourceTest(APITestCase):
    def setUp(self):
        """
        Set up for the Acknowledgement Test

        Objects created:
        -User
        -Customer
        -Supplier
        -Address
        -product
        -2 fabrics

        After Creating all the needed objects for the Acknowledgement, 
        test that all the objects have been made.
        """
        super(ShippingResourceTest, self).setUp()

        self.ct = ContentType(app_label="shipping")
        self.ct.save()

        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, '*****@*****.**',
                                             self.password)
        self.user.save()

        p = Permission(content_type=self.ct, codename="change_shipping")
        p.save()
        p2 = Permission(content_type=self.ct, codename="add_shipping")
        p2.save()
        self.user.user_permissions.add(p)
        self.user.user_permissions.add(p2)

        self.user.save()

        self.setup_client()

        #Create supplier, customer and addrss
        self.customer = Customer(**base_customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()

        #Create project
        self.project = Project.objects.create(codename="Ladawan")

        #Create phase
        self.phase = Phase.objects.create(description="Phase 1/6",
                                          project=self.project)

        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()
        self.fabric = Fabric.create(**base_fabric)
        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)

        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        self.ack = Acknowledgement(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()

        #Create an item
        item_data = {
            'id': 1,
            'quantity': 1,
            'is_custom_size': True,
            'width': 1500,
            "fabric": {
                "id": 1
            }
        }
        self.item = AckItem.create(acknowledgement=self.ack, **item_data)

        #Create an item
        item_data = {
            'id': 1,
            'quantity': 2,
            'is_custom_size': True,
            'width': 1500,
            "fabric": {
                "id": 1
            }
        }
        self.item2 = AckItem.create(acknowledgement=self.ack, **item_data)

    def create_shipping(self):
        #create a shipping item
        self.shipping = Shipping.create(acknowledgement={'id': 1},
                                        customer={'id': 1},
                                        user=self.user,
                                        delivery_date=base_delivery_date,
                                        items=[{
                                            'id': 1
                                        }, {
                                            'id': 2
                                        }])
        self.shipping.save()

    def get_credentials(self):
        return self.user  #self.create_basic(username=self.username, password=self.password)

    def setup_client(self):
        # Login the Client

        # APIClient
        #self.client = APIClient(enforce_csrf_checks=False)
        #self.client.login(username=self.username, password=self.password)
        self.client.force_authenticate(self.user)

    def test_get_list(self):
        """
        Tests getting a list of objects via GET
        """
        self.skipTest('')
        #Create a shipping to retrieve
        self.create_shipping()

        resp = self.client.get('/api/v1/shipping/',
                               format='json',
                               authentication=self.get_credentials())
        self.assertEqual(resp.status_code, 200)

        #Validate the resources returned
        resp_obj = resp.data
        self.assertEqual(len(resp_obj['objects']), 1)

    def test_get(self):
        """
        Tests getting an object via GET
        """
        self.skipTest('')
        self.create_shipping()

        #Test the resp
        resp = self.client.get('/api/v1/shipping/1/',
                               format='json',
                               authentication=self.get_credentials())
        self.assertEqual(resp.status_code, 200)

        #Validate the object
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertIn("customer", obj)
        self.assertEqual(obj['customer']['id'], 1)

    def test_post_project_shipping(self):
        """
        Test creating a project packing list via POST
        """
        data = {
            'project': {
                'id': 1
            },
            'customer': {
                'id': 1
            },
            'phase': {
                'id': 1
            },
            'items': [{
                'description': 'TK 1/2'
            }]
        }

        resp = self.client.post('/api/v1/shipping/', format='json', data=data)

        # Test client response
        self.assertEqual(resp.status_code, 201, msg=resp)

    def test_post_with_two_item(self):
        """
        Tests creating a resource via POST
        """
        #Validate the resp and obj creation
        self.assertEqual(Shipping.objects.count(), 0)
        shipping_data = {
            'acknowledgement': {
                'id': 1
            },
            'customer': {
                'id': 1
            },
            'delivery_date':
            base_delivery_date,
            'items': [{
                'item': {
                    'id': 1
                },
                'description': 'test1',
                'quantity': 1
            }, {
                'item': {
                    'id': 2
                }
            }]
        }
        resp = self.client.post('/api/v1/shipping/',
                                data=shipping_data,
                                format='json')

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Shipping.objects.count(), 1)

        #validate the object returned
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertIn('customer', obj)
        self.assertEqual(obj['customer']['id'], 1)
        self.assertIn('last_modified', obj)
        self.assertIn('time_created', obj)
        self.assertEqual(len(obj['items']), 2)
        item1 = obj['items'][0]

        #Validate resource in the database
        shipping = Shipping.objects.get(pk=1)
        self.assertEqual(shipping.id, 1)
        self.assertEqual(shipping.customer.id, 1)
        self.assertEqual(shipping.items.count(), 2)

    def test_post_with_one_item(self):
        """
        Tests creating a resource via POST
        """
        #Validate the resp and obj creation
        self.assertEqual(Shipping.objects.count(), 0)
        shipping_data = {
            'acknowledgement': {
                'id': 1
            },
            'customer': {
                'id': 1
            },
            'delivery_date': base_delivery_date,
            'items': [{
                'item': {
                    'id': 1
                },
                'description': 'test1',
                'quantity': 1
            }]
        }
        resp = self.client.post('/api/v1/shipping/',
                                data=shipping_data,
                                format='json')

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Shipping.objects.count(), 1)

        #validate the object returned
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertIn('customer', obj)
        self.assertEqual(obj['customer']['id'], 1)
        self.assertIn('last_modified', obj)
        self.assertIn('time_created', obj)
        self.assertEqual(len(obj['items']), 1)
        item1 = obj['items'][0]

        #Validate resource in the database
        shipping = Shipping.objects.get(pk=1)
        self.assertEqual(shipping.id, 1)
        self.assertEqual(shipping.customer.id, 1)
        self.assertEqual(shipping.items.count(), 1)

    def test_put(self):
        """
        Tests updating a resource via PUT
        """
        self.skipTest('')
        self.create_shipping()
        self.assertEqual(Shipping.objects.count(), 1)
        resp = self.client.put('/api/v1/shipping/1/',
                               format='json',
                               authentication=self.get_credentials(),
                               data={
                                   'delivery_date': base_delivery_date,
                                   'acknowledgement': {
                                       'id': 1
                                   }
                               })
        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Shipping.objects.count(), 1)

        #Validate the obj
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertEqual(obj['customer']['id'], 1)
        self.assertEqual(obj['comments'], 'test')

    def test_delete(self):
        """
        Tests deleting a resource via DELETE
        """
        self.skipTest('')
        self.create_shipping()
        self.assertEqual(Shipping.objects.count(), 1)
        resp = self.client.delete('/api/v1/shipping/1/',
                                  format='json',
                                  authentication=self.get_credentials())
        self.assertEqual(resp.status_code, 204)
        self.assertEqual(Shipping.objects.count(), 0)
Esempio n. 19
0
class EstimateResourceTest(APITestCase):
    """"
    This tests the api acknowledgements:
    
    GET list:
    -get a list of objects
    -objects have items and items have pillows
    
    GET:
    -the acknowledgement has delivery date, order date
    customer, status, grand_total, vat, employee, discount
    -the acknowledgement has a list of items.
    -The items have pillows and fabrics
    -pillows have fabrics
    -the items has dimensions, pillows, fabric, comments
    price per item
    
    POST:
    -create an acknowledgement that has delivery date, order date
    customer, status, grand_total, vat, employee, discount, items
    -the items should have fabrics and pillows where appropriate
    """
    def setUp(self):
        """
        Set up for the Estimate Test

        Objects created:
        -User
        -Customer
        -Supplier
        -Address
        -product
        -2 fabrics

        After Creating all the needed objects for the Estimate, 
        test that all the objects have been made.
        """
        super(EstimateResourceTest, self).setUp()

        # Set Base URL
        self.base_url = '{0}'.format('/api/v1/estimate/')

        self.ct = ContentType(app_label="estimates")
        self.ct.save()
        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, '*****@*****.**',
                                             self.password)
        p = Permission(content_type=self.ct, codename="change_estimate")
        p.save()
        p2 = Permission(content_type=self.ct, codename="add_estimate")
        p2.save()
        self.user.user_permissions.add(p)
        self.user.user_permissions.add(p2)

        self.user.save()

        self.setup_client()

        #Create supplier, customer and addrss
        customer = copy.deepcopy(base_customer)
        del customer['id']
        self.customer = Customer(**customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()

        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()

        #Create custom product
        self.custom_product = Product()
        self.custom_product.id = 10436
        self.custom_product.save()

        self.fabric = Fabric.create(**base_fabric)
        self.fabric.quantity = 26
        self.fabric.save()

        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)

        #Create custom product
        self.custom_product = Product.create(self.user,
                                             description="Custom Custom",
                                             id=10436,
                                             width=0,
                                             depth=0,
                                             height=0,
                                             price=0,
                                             wholesale_price=0,
                                             retail_price=0)
        self.custom_product.id = 10436
        self.custom_product.save()

        self.image = S3Object(key='test', bucket='test')
        self.image.save()

        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        del ack_data['project']
        self.ack = Estimate(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()

        #Create an item
        item_data = {
            'id': 1,
            'quantity': 1,
            'is_custom_size': True,
            'width': 1500,
            "fabric": {
                "id": 1
            }
        }
        self.item = Item.create(estimate=self.ack, **item_data)
        item_data = {
            'is_custom': True,
            'description': 'F-04 Sofa',
            'quantity': 3
        }
        self.item2 = Item.create(estimate=self.ack, **item_data)

        #Create fake S3Objects to test files attached to acknowledgements
        self.file1 = S3Object(key='test1', bucket='test')
        self.file2 = S3Object(key='test2', bucket='test')
        self.file1.save()
        self.file2.save()

    def setup_client(self):
        # Login the Client

        # APIClient
        #self.client = APIClient(enforce_csrf_checks=False)
        #self.client.login(username=self.username, password=self.password)
        self.client.force_authenticate(self.user)

        # RequestsClient
        """
        logger.debug(self)
        self.client = RequestsClient()
        self.client.auth = HTTPBasicAuth(self.username, self.password)
        logger.debug(self.client.__dict__)

        # Obtain a CSRF token.
        response = self.client.post("{0}{1}".format(self.live_server_url,'/login'), 
                                    data={'username': self.username,
                                          'password': self.password})
        logger.debug(response.cookies['csrftoken'])
        assert response.status_code == 200
        csrftoken = response.cookies['csrftoken']
        self.client.headers.update({'X-CSRFTOKEN': csrftoken})
        logger.debug(self.client.__dict__)
        """

    def get_credentials(self):
        return self.user

    def open_url(self, url):
        pass  #webbrowser.open(url)

    def test_get_list(self):
        """
        Tests getting the list of acknowledgements
        """
        #Get and verify the resp
        resp = self.client.get(self.base_url)
        self.assertEqual(resp.status_code, 200, msg=resp)
        logger.debug(resp)
        #Verify the data sent
        quotations = resp.data
        self.assertIsNotNone(quotations)
        self.assertEqual(len(quotations), 1)
        self.assertEqual(len(quotations[0]['items']), 2)

    def test_get(self):
        """
        Tests getting the acknowledgement
        """
        #Get and verify the resp
        resp = self.client.get("{0}1/".format(self.base_url))
        self.assertEqual(resp.status_code, 200, msg=resp)

        #Verify the data sent
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 1)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(dateutil.parser.parse(ack['delivery_date']),
                         base_delivery_date)
        self.assertEqual(Decimal(ack['vat']), 0)
        self.assertEqual(Decimal(ack['grand_total']), Decimal(0))

    def xtest_post_dr_vs_pci(self):
        """
        Test POSTING ack with company as 'Dellarobbia Thailand' vs 'Pacific Carpet'
        """
        logger.debug(
            "\n\n Testing creating acknowledgement with diferring companies\n")
        ack1_data = copy.deepcopy(base_ack)
        ack1_data['company'] = 'Dellarobbia Thailand'
        ack

    def test_post_with_discount_on_data(self):
        """
        Testing POSTing data to the api
        """
        logger.debug(
            "\n\n Testing creating acknowledgement with a discount \n")

        modified_data = copy.deepcopy(base_ack)
        modified_data['discount'] = 50
        modified_data['items'][-1]['fabric'] = {'id': 1, 'image': {'id': 1}}
        modified_data['items'][-1]['fabric_quantity'] = 8
        modified_data['files'] = [{'id': 1}, {'id': 2}]

        #POST and verify the response
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/',
                                data=modified_data,
                                format='json')

        #Verify that http response is appropriate
        self.assertEqual(resp.status_code, 201, msg=resp)

        #Verify that an acknowledgement is created in the system
        self.assertEqual(Estimate.objects.count(), 2)

        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(Decimal(Decimal(ack['vat'])), Decimal(0))
        self.assertEqual(Decimal(ack['subtotal']), Decimal(300000))
        self.assertEqual(Decimal(ack['total']), Decimal(150000))
        self.assertEqual(Decimal(ack['grand_total']), Decimal(150000))
        self.assertEqual(len(ack['items']), 3)
        self.assertIn('project', ack)
        self.assertEqual(ack['project']['id'], 1)
        self.assertEqual(ack['project']['codename'], 'Ladawan1')
        #self.assertIsInstance(ack['files'], list)
        #self.assertEqual(len(ack['files']), 2)

        #Test standard sized item
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(Decimal(item1['quantity']), Decimal('2.00'))
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertIn('total', item1)
        self.assertEqual(Decimal(item1['total']), Decimal(200000))

        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(Decimal(item2['quantity']), Decimal('1.00'))
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item2['total']), Decimal(100000))

        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertEqual(Decimal(item3['quantity']), Decimal('1.00'))
        self.assertEqual(Decimal(item3['unit_price']), 0)
        self.assertEqual(item3['fabric']['id'], 1)

        #Tests links to document
        """
        self.assertIsNotNone(ack['pdf'])
        self.assertIsNotNone(ack['pdf']['acknowledgement'])
        self.assertIsNotNone(ack['pdf']['production'])
        self.assertIsNotNone(ack['pdf']['confirmation'])
        """

        #Tests the acknowledgement in the database
        root_ack = Estimate.objects.get(pk=2)
        logger.debug(root_ack.project)
        self.assertEqual(root_ack.id, 2)
        self.assertEqual(root_ack.items.count(), 3)
        self.assertIsInstance(root_ack.project, Project)
        self.assertEqual(root_ack.project.id, 1)
        self.assertEqual(root_ack.project.codename, "Ladawan1")
        root_ack_items = root_ack.items.all()
        item1 = root_ack_items[0]
        item2 = root_ack_items[1]
        item3 = root_ack_items[2]
        self.assertEqual(item1.estimate.id, 2)
        self.assertEqual(item1.description, 'Test Sofa Max')
        self.assertEqual(item1.quantity, 2)
        self.assertEqual(item1.width, 1000)
        self.assertEqual(item1.height, 320)
        self.assertEqual(item1.depth, 760)
        self.assertEqual(item2.estimate.id, 2)
        self.assertEqual(item2.description, 'High Gloss Table')
        self.assertEqual(item2.width, 1500)
        self.assertEqual(item2.height, 320)
        self.assertEqual(item2.depth, 760)
        self.assertEqual(item3.estimate.id, 2)
        self.assertEqual(item3.description, 'test custom item')
        self.assertEqual(item3.width, 1)
        self.assertEqual(item3.quantity, 1)

        #Tests files attached to acknowledgements
        """
        self.assertEqual(root_ack.files.all().count(), 2)
        file1 = root_ack.files.all()[0]
        self.assertEqual(file1.id, 1)
        file2 = root_ack.files.all()[1]
        self.assertEqual(file2.id, 2)
        
        #Test Fabric Log
        self.assertEqual(Log.objects.filter(acknowledgement_id=root_ack.id).count(), 1)
        log = Log.objects.get(acknowledgement_id=root_ack.id)
        self.assertEqual(log.quantity, Decimal('33'))
        self.assertEqual(log.action, 'RESERVE')
        self.assertEqual(log.acknowledgement_id, '2')
        self.assertEqual(log.message, 'Reserve 33m of Pattern: Max, Col: charcoal for Ack#2')
        self.assertEqual(Fabric.objects.get(id=1).quantity, Decimal('-7'))
        """
        self.open_url(ack['files'][0]['url'])

    def test_post_with_custom_image(self):
        """
        Testing POSTing data to the api with custom item with custom image
        """

        logger.debug(
            "\n\n Testing creating acknowledgement with a custom image \n")
        #Apply a discount to the customer
        ack = copy.deepcopy(base_ack)
        ack['items'][2]['image'] = {'id': 1}

        #POST and verify the response
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/', data=ack, format='json')

        #Verify that http response is appropriate
        self.assertEqual(resp.status_code, 201, msg=resp)

        #Verify that an acknowledgement is created in the system
        self.assertEqual(Estimate.objects.count(), 2)

        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(Decimal(ack['vat']), 0)
        self.assertEqual(Decimal(ack['grand_total']), Decimal(300000))
        self.assertEqual(len(ack['items']), 3)
        self.assertIn('project', ack)
        self.assertEqual(ack['project']['id'], 1)
        self.assertEqual(ack['project']['codename'], 'Ladawan1')

        #Test standard sized item
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(Decimal(item1['quantity']), Decimal('2.00'))
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item1['total']), Decimal(200000))

        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(Decimal(item2['quantity']), Decimal('1.00'))
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item2['total']), Decimal(100000))

        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertEqual(Decimal(item3['quantity']), Decimal('1.00'))
        self.assertEqual(Decimal(item3['unit_price']), 0)
        self.assertIsNotNone(item3['image'])
        self.assertIn('url', item3['image'])

        #Tests links to document
        #self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])
        #logger.debug(ack['pdf']['confirmation'])
        #print "\n\n\n"

        #Tests the acknowledgement in the database
        root_ack = Estimate.objects.get(pk=2)
        logger.debug(root_ack.project)
        self.assertEqual(root_ack.id, 2)
        self.assertEqual(root_ack.items.count(), 3)
        self.assertIsInstance(root_ack.project, Project)
        self.assertEqual(root_ack.project.id, 1)
        self.assertEqual(root_ack.project.codename, "Ladawan1")
        root_ack_items = root_ack.items.all()
        item1 = root_ack_items[0]
        item2 = root_ack_items[1]
        item3 = root_ack_items[2]
        self.assertEqual(item1.estimate.id, 2)
        self.assertEqual(item1.description, 'Test Sofa Max')
        self.assertEqual(item1.quantity, 2)
        self.assertEqual(item1.width, 1000)
        self.assertEqual(item1.height, 320)
        self.assertEqual(item1.depth, 760)
        self.assertEqual(item2.estimate.id, 2)
        self.assertEqual(item2.description, 'High Gloss Table')
        self.assertEqual(item2.width, 1500)
        self.assertEqual(item2.height, 320)
        self.assertEqual(item2.depth, 760)
        self.assertEqual(item3.estimate.id, 2)
        self.assertEqual(item3.description, 'test custom item')
        self.assertEqual(item3.width, 1)
        self.assertEqual(item3.quantity, 1)

    def test_post_without_vat(self):
        """
        Testing POSTing data to the api
        """
        logger.debug("\n\n Testing creating acknowledgement without vat \n")

        #POST and verify the response
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/',
                                format='json',
                                data=base_ack,
                                authentication=self.get_credentials())

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Estimate.objects.count(), 2)

        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(Decimal(ack['vat']), 0)
        self.assertEqual(Decimal(ack['grand_total']), Decimal('300000'))
        self.assertEqual(len(ack['items']), 3)
        self.assertIn('project', ack)
        self.assertEqual(ack['project']['id'], 1)
        self.assertEqual(ack['project']['codename'], 'Ladawan1')

        #Test standard sized item
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(Decimal(item1['quantity']), Decimal('2.00'))
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item1['total']), Decimal(200000))

        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(Decimal(item2['quantity']), Decimal('1.00'))
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item2['total']), Decimal(100000))

        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertEqual(Decimal(item3['quantity']), Decimal('1.00'))
        self.assertEqual(Decimal(item3['unit_price']), 0)

        #Tests links to document
        #self.assertIsNotNone(ack['pdf'])
        #?self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])

        self.open_url(ack['files'][0]['url'])

    def test_post_with_vat(self):
        """
        Testing POSTing data to the api if there
        is vat
        """
        logger.debug("\n\n Testing creating acknowledgement with vat \n")

        #Altering replication of base ack data
        ack_data = base_ack.copy()
        ack_data['vat'] = 7

        #Verifying current number of acknowledgements in database
        self.assertEqual(Estimate.objects.count(), 1)

        resp = self.client.post('/api/v1/estimate/',
                                format='json',
                                data=ack_data,
                                authentication=self.get_credentials())

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

        self.assertEqual(Estimate.objects.count(), 2)

        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(Decimal(ack['vat']), 7)
        self.assertEqual(Decimal(ack['grand_total']), Decimal(321000.00))
        self.assertEqual(len(ack['items']), 3)
        self.assertIn('project', ack)
        self.assertEqual(ack['project']['id'], 1)
        self.assertEqual(ack['project']['codename'], 'Ladawan1')

        #Test standard sized item
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(Decimal(item1['quantity']), Decimal('2'))
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item1['total']), Decimal(200000))

        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(Decimal(item2['quantity']), Decimal('1.00'))
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item2['total']), Decimal(100000))

        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertEqual(Decimal(item3['quantity']), Decimal('1.00'))
        self.assertEqual(Decimal(item3['unit_price']), 0)

        #Tests links to document
        #self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])
        self.open_url(ack['files'][0]['url'])

    def test_post_with_vat_and_discount(self):
        """
        Testing POSTing data to the api if there
        is vat
        """
        logger.debug(
            "\n\n Testing creating acknowledgement with a discount and vat \n")

        #POST and verify the response
        ack_data = base_ack.copy()
        ack_data['vat'] = 7
        ack_data['discount'] = 50
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/',
                                format='json',
                                data=ack_data,
                                authentication=self.get_credentials())

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Estimate.objects.count(), 2)

        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(Decimal(ack['vat']), Decimal(7))
        self.assertEqual(Decimal(ack['subtotal']), Decimal('300000'))
        self.assertEqual(Decimal(ack['discount_amount']), Decimal('150000'))
        self.assertEqual(Decimal(ack['post_discount_total']),
                         Decimal('150000'))
        self.assertEqual(Decimal(ack['total']), Decimal('150000'))
        self.assertEqual(Decimal(ack['vat_amount']), Decimal('10500'))
        self.assertEqual(Decimal(ack['grand_total']), Decimal('160500.000'))
        self.assertEqual(len(ack['items']), 3)

        #Test standard sized item
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(Decimal(item1['quantity']), 2)
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertIn('total', item1, item1)
        self.assertEqual(Decimal(item1['total']), Decimal(200000))

        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(Decimal(item2['quantity']), Decimal('1.00'))
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']),
                         Decimal(100000))  # No longer Caculates Custom Size
        self.assertEqual(Decimal(item2['total']), Decimal(100000))

        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertEqual(Decimal(item3['quantity']), Decimal('1.00'))
        self.assertEqual(Decimal(item3['unit_price']), 0)

        #Tests links to document
        #self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])

        self.open_url(ack['files'][0]['url'])

    def test_post_with_vat_and_both_discounts(self):
        """
        Testing POSTing data to the api if there
        is vat
        """
        logger.debug(
            "\n\n Testing creating acknowledgement with both discounts and vat \n"
        )

        #POST and verify the response
        ack_data = base_ack.copy()
        ack_data['vat'] = 7
        ack_data['discount'] = 50
        ack_data['second_discount'] = 10
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/',
                                format='json',
                                data=ack_data,
                                authentication=self.get_credentials())

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Estimate.objects.count(), 2)

        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(Decimal(ack['vat']), Decimal(7))
        self.assertEqual(Decimal(ack['subtotal']), Decimal('300000'))
        self.assertEqual(Decimal(ack['discount_amount']), Decimal('150000'))
        self.assertEqual(Decimal(ack['post_discount_total']),
                         Decimal('150000'))
        self.assertEqual(Decimal(ack['second_discount_amount']),
                         Decimal('15000'))
        self.assertEqual(Decimal(ack['total']), Decimal('135000'))
        self.assertEqual(Decimal(ack['vat_amount']), Decimal('9450'))
        self.assertEqual(Decimal(ack['grand_total']), Decimal('144450.000'))
        self.assertEqual(len(ack['items']), 3)

        #Test standard sized item
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(Decimal(item1['quantity']), 2)
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item1['total']), Decimal(200000))

        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(Decimal(item2['quantity']), Decimal('1.00'))
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']),
                         Decimal(100000))  # No longer Caculates Custom Size
        self.assertEqual(Decimal(item2['total']), Decimal(100000))

        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertEqual(Decimal(item3['quantity']), Decimal('1.00'))
        self.assertEqual(Decimal(item3['unit_price']), 0)

        #Tests links to document
        #self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])
        self.open_url(ack['files'][0]['url'])

    def test_post_with_custom_price(self):
        """
        Test creating a custom price for all three item types
        """
        logger.debug(
            "\n\n Testing creating acknowledgement with custom prices for all items \n"
        )

        #POST and verify the response
        ack_data = copy.deepcopy(base_ack)
        ack_data['items'][0]['unit_price'] = 100
        ack_data['items'][1]['unit_price'] = 200
        ack_data['items'][2]['unit_price'] = 300

        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/',
                                format='json',
                                data=ack_data,
                                authentication=self.get_credentials())

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Estimate.objects.count(), 2)

        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(Decimal(ack['vat']), 0)
        self.assertEqual(Decimal(ack['grand_total']), Decimal('700.00'))
        self.assertEqual(len(ack['items']), 3)

        #Test standard sized item
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(Decimal(item1['quantity']), 2)
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal('100'))
        self.assertEqual(Decimal(item1['total']), Decimal('200'))

        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(Decimal(item2['quantity']), Decimal('1.00'))
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal('200'))
        self.assertEqual(Decimal(item2['total']), Decimal('200'))

        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertEqual(Decimal(item3['quantity']), Decimal('1.00'))
        self.assertEqual(Decimal(item3['unit_price']), Decimal('300'))

        #Tests links to document
        #self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])

    def test_post_where_first_item_has_no_fabric(self):
        """
        Test creating a custom price for all three item types
        """
        logger.debug(
            "\n\n Testing creating acknowledgement with custom prices for all items \n"
        )

        #POST and verify the response
        ack_data = copy.deepcopy(base_ack)
        del ack_data['items'][0]['fabric']
        del ack_data['items'][0]['pillows'][0]['fabric']

        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/',
                                format='json',
                                data=ack_data,
                                authentication=self.get_credentials())

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Estimate.objects.count(), 2)

        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(Decimal(ack['vat']), 0)
        self.assertEqual(Decimal(ack['grand_total']), Decimal('300000'))
        self.assertEqual(len(ack['items']), 3)

        #Test standard sized item
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(Decimal(item1['quantity']), Decimal('2.00'))
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertIsNone(item1['fabric'])
        self.assertEqual(len(item1['pillows']), 5)
        self.assertEqual(Decimal(item1['unit_price']), Decimal('100000'))
        self.assertEqual(Decimal(item1['total']), Decimal('200000'))

        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(Decimal(item2['quantity']), Decimal('1.00'))
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal('100000'))
        self.assertEqual(Decimal(item2['total']), Decimal('100000'))

        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertEqual(Decimal(item3['quantity']), Decimal('1.00'))

        #Tests links to document

        #self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])

    def test_put(self):
        """
        Test making a PUT call
        """
        logger.debug("\n\n Testing updating via put \n")

        ack_data = base_ack.copy()
        ack_data['items'][0]['id'] = 1
        del ack_data['items'][0]['pillows'][-1]
        ack_data['items'][1]['id'] = 2
        ack_data['items'][1]['description'] = 'F-04 Sofa'
        ack_data['items'][1]['is_custom_item'] = True
        del ack_data['items'][2]
        ack_data['delivery_date'] = datetime.now()
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.put('/api/v1/estimate/1/',
                               format='json',
                               data=ack_data,
                               authentication=self.get_credentials())

        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Estimate.objects.count(), 1)

        #Validate the change
        ack = resp.data
        #self.assertEqual(dateutil.parser.parse(ack['delivery_date']), ack_data['delivery_date'])
        logger.debug(ack['items'][0]['pillows'])
        #Tests ack in database
        ack = Estimate.objects.get(pk=1)
        items = ack.items.all()

        item1 = items[0]
        self.assertEqual(item1.description, 'Test Sofa Max')
        #self.assertEqual(item1.pillows.count(), 3)

        item2 = items[1]
        self.assertEqual(item2.description, 'F-04 Sofa')

    def test_changing_lead_time(self):
        """
        Test making a PUT call
        """
        logger.debug("\n\n Testing updating lead time via put \n")

        ack_data = copy.deepcopy(base_ack)

        ack_data['lead_time'] = '6 Weeks'
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.put('/api/v1/estimate/1/',
                               format='json',
                               data=ack_data,
                               authentication=self.get_credentials())

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

        ack = resp.data
        #logger.debug(ack['delivery_date'])
        #d1 = datetime.strptime(ack['delivery_date'])

        self.assertEqual(ack['lead_time'], '6 Weeks')

        ack = Estimate.objects.all()[0]
        self.assertEqual(ack.lead_time, '6 Weeks')

    #@unittest.skip('ok')
    def test_delete(self):
        """
        Test making a DELETE call
        
        'Delete' in this model has been overridden so that no acknowledgement 
        is truly deleted. Instead the 'delete' column in the database is marked 
        as true
        """
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.delete('/api/v1/estimate/1/',
                                  authentication=self.get_credentials())

        self.assertEqual(Estimate.objects.count(), 1)
Esempio n. 20
0
class TestItemResource(APITestCase):
    def setUp(self):
        """
        Sets up environment for tests
        """
        super(TestItemResource, self).setUp()

        self.create_user()

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

        #Create supplier, customer and addrss
        self.customer = Customer(**base_customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()

        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()
        self.fabric = Fabric.create(**base_fabric)
        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)

        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        del ack_data['project']
        self.ack = Estimate(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()

        #Create an item
        self.item_data = {
            'id': 1,
            'quantity': 1,
            'is_custom_size': True,
            'width': 1500,
            "fabric": {
                "id": 1
            }
        }
        self.item = Item.create(acknowledgement=self.ack, **self.item_data)

    def create_user(self):
        self.user = User.objects.create_user('test', '*****@*****.**', 'test')
        self.ct = ContentType(app_label='acknowledgements')
        self.ct.save()
        perm = Permission(content_type=self.ct, codename='change_item')
        perm.save()
        self.user.user_permissions.add(perm)
        perm = Permission(content_type=self.ct, codename='change_fabric')
        perm.save()
        self.user.user_permissions.add(perm)
        self.assertTrue(self.user.has_perm('acknowledgements.change_item'))
        return self.user

    def test_get_list(self):
        """
        Tests getting a list of items via GET
        """
        #Tests the get
        resp = self.client.get('/api/v1/acknowledgement-item')
        #self.assertHttpOK(resp)

        #Tests the resp
        resp_obj = self.deserialize(resp)
        self.assertIn("objects", resp_obj)
        self.assertEqual(len(resp_obj['objects']), 1)

    def test_get(self):
        """
        Tests getting an item via GET
        """
        #Tests the resp
        resp = self.client.get('/api/v1/acknowledgement-item/1')
        #self.assertHttpOK(resp)

    def test_failed_create(self):
        """
        Tests that when attempting to create via POST
        it is returned as unauthorized
        """
        resp = self.client.post('/api/v1/acknowledgement-item/',
                                format='json',
                                data=self.item_data)
        #self.assertHttpMethodNotAllowed(resp)

    def test_update(self):
        """
        Tests updating the item via PUT
        """
        modified_item_data = self.item_data.copy()
        modified_item_data['fabric'] = {'id': 2}
        modified_item_data['width'] = 888

        #Sets current fabric
        self.assertEqual(Item.objects.all()[0].fabric.id, 1)

        #Tests the response
        resp = self.client.put('/api/v1/acknowledgement-item/1',
                               format='json',
                               data=modified_item_data)
        #self.assertHttpOK(resp)
        self.assertEqual(Item.objects.all()[0].fabric.id, 2)

        #Tests the data returned
        obj = self.deserialize(resp)
        self.assertEqual(obj['id'], 1)
        self.assertEqual(obj['fabric']['id'], 2)
        self.assertEqual(obj['width'], 888)
        self.assertEqual(obj['quantity'], 1)
Esempio n. 21
0
    def setUp(self):
        """
        Set up for the Estimate Test

        Objects created:
        -User
        -Customer
        -Supplier
        -Address
        -product
        -2 fabrics

        After Creating all the needed objects for the Estimate, 
        test that all the objects have been made.
        """
        super(EstimateResourceTest, self).setUp()

        self.ct = ContentType(app_label="estimates")
        self.ct.save()
        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, '*****@*****.**', self.password)
        p = Permission(content_type=self.ct, codename="change_estimate")
        p.save()
        p2 = Permission(content_type=self.ct, codename="add_estimate")
        p2.save()
        self.user.user_permissions.add(p)
        self.user.user_permissions.add(p2)
        
        self.user.save()
        
        #Create supplier, customer and addrss
        customer = copy.deepcopy(base_customer)
        del customer['id']
        self.customer = Customer(**customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()
        
        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()
        
        #Create custom product
        self.custom_product = Product()
        self.custom_product.id = 10436
        self.custom_product.save()
        
        self.fabric = Fabric.create(**base_fabric)
        self.fabric.quantity = 26
        self.fabric.save()
        
        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)
        
        #Create custom product
        self.custom_product = Product.create(self.user, description="Custom Custom", id=10436,
                                             width=0, depth=0, height=0,
                                             price=0, wholesale_price=0, retail_price=0)
        self.custom_product.id = 10436
        self.custom_product.save()
        
        self.image = S3Object(key='test', bucket='test')
        self.image.save()
        
        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        del ack_data['project']
        self.ack = Estimate(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()
        
        #Create an item
        item_data = {'id': 1,
                     'quantity': 1,
                     'is_custom_size': True,
                     'width': 1500,
                     "fabric": {"id":1}}
        self.item = Item.create(estimate=self.ack, **item_data)
        item_data = {'is_custom': True,
                     'description': 'F-04 Sofa',
                     'quantity': 3}
        self.item2 = Item.create(estimate=self.ack, **item_data)
        self.client.login(username="******", password="******")
        
        #Create fake S3Objects to test files attached to acknowledgements
        self.file1 = S3Object(key='test1', bucket='test')
        self.file2 = S3Object(key='test2', bucket='test')
        self.file1.save()
        self.file2.save()
Esempio 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.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")
Esempio n. 23
0
class TestItemResource(APITestCase):
    def setUp(self):
        """
        Sets up environment for tests
        """
        super(TestItemResource, self).setUp()
        
        self.create_user()
        
        self.client.login(username='******', password='******')
        
        #Create supplier, customer and addrss
        self.customer = Customer(**base_customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()
        
        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()
        self.fabric = Fabric.create(**base_fabric)
        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)
        
        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        del ack_data['project']
        self.ack = Estimate(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()
        
        #Create an item
        self.item_data = {'id': 1,
                     'quantity': 1,
                     'is_custom_size': True,
                     'width': 1500,
                     "fabric": {"id":1}}
        self.item = Item.create(acknowledgement=self.ack, **self.item_data)
        
    def create_user(self):
        self.user = User.objects.create_user('test', '*****@*****.**', 'test')
        self.ct = ContentType(app_label='acknowledgements')
        self.ct.save()
        perm = Permission(content_type=self.ct, codename='change_item')
        perm.save()
        self.user.user_permissions.add(perm)
        perm = Permission(content_type=self.ct, codename='change_fabric')
        perm.save()
        self.user.user_permissions.add(perm)
        self.assertTrue(self.user.has_perm('acknowledgements.change_item'))
        return self.user
        
    def test_get_list(self):
        """
        Tests getting a list of items via GET
        """
        #Tests the get
        resp = self.client.get('/api/v1/acknowledgement-item')
        #self.assertHttpOK(resp)
        
        #Tests the resp
        resp_obj = self.deserialize(resp)
        self.assertIn("objects", resp_obj)
        self.assertEqual(len(resp_obj['objects']), 1)
        
    def test_get(self):
        """
        Tests getting an item via GET
        """
        #Tests the resp
        resp = self.client.get('/api/v1/acknowledgement-item/1')
        #self.assertHttpOK(resp)
        
    def test_failed_create(self):
        """
        Tests that when attempting to create via POST
        it is returned as unauthorized
        """
        resp = self.client.post('/api/v1/acknowledgement-item/', format='json',
                                    data=self.item_data)
        #self.assertHttpMethodNotAllowed(resp)
        
    def test_update(self):
        """
        Tests updating the item via PUT
        """
        modified_item_data = self.item_data.copy()
        modified_item_data['fabric'] = {'id': 2}
        modified_item_data['width'] = 888
        
        #Sets current fabric
        self.assertEqual(Item.objects.all()[0].fabric.id, 1)
        
        #Tests the response
        resp = self.client.put('/api/v1/acknowledgement-item/1', format='json',
                                   data=modified_item_data)
        #self.assertHttpOK(resp)
        self.assertEqual(Item.objects.all()[0].fabric.id, 2)
        
        #Tests the data returned
        obj = self.deserialize(resp)
        self.assertEqual(obj['id'], 1)
        self.assertEqual(obj['fabric']['id'], 2)
        self.assertEqual(obj['width'], 888)
        self.assertEqual(obj['quantity'], 1)
Esempio n. 24
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'))
Esempio n. 25
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)
Esempio n. 26
0
class GroupResourceTest(ResourceTestCase):
    def setUp(self):
        """
        Set up the environment for the test cases
        """
        super(GroupResourceTest, self).setUp()
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_superuser('tester',
                                                  '*****@*****.**', 'test')
        self.user.user_permissions.add(
            Permission.objects.get(codename="add_user"))
        self.api_client.client.login(username='******', password='******')

        #Create a group
        self.group = Group(name="God")
        self.group.save()

        #Create a permission
        self.ct = ContentType(name='test')
        self.ct.save()
        self.permission = Permission(name='Test',
                                     codename='test',
                                     content_type=self.ct)
        self.permission.save()

        self.group.permissions.add(self.permission)

    def test_get_list(self):
        """
        Tests getting a list of groups via GET
        """
        #Tests the resp
        resp = self.api_client.get('/api/v1/group/')
        self.assertHttpOK(resp)

    def test_get(self):
        """
        Tests getting a group via GET
        """
        #Tests the resp
        resp = self.api_client.get('/api/v1/group/1/')
        self.assertHttpOK(resp)

        #Tests the return data
        group = self.deserialize(resp)
        self.assertEqual(group['id'], 1)
        self.assertEqual(group['name'], 'God')
        self.assertIn('permissions', group)
        self.assertEqual(len(group['permissions']), 1)

    def test_post(self):
        """
        Test creating a new group via POST
        """
        #Test the api and the respose
        self.assertEqual(Group.objects.count(), 1)
        resp = self.api_client.post('/api/v1/group/',
                                    format='json',
                                    data={
                                        'name': 'Boss',
                                        'group': 'Boss',
                                        'permissions': [{
                                            'id': 1
                                        }]
                                    })
        self.assertHttpCreated(resp)
        self.assertEqual(Group.objects.count(), 2)
        self.assertEqual(
            Group.objects.order_by('-id').all()[0].permissions.count(), 1)

        #Tests the data to be returned
        self.assertEqual(group['id'], 2)
        self.assertEqual(group['name'], 'Boss')
        self.assertIn('permissions', group)
        self.assertEqual(len(group['permissions']), 1)
        self.assertEqual(group['permissions'][0]['name'],
                         Permission.objects.get(pk=1).name)
Esempio n. 27
0
class ShippingResourceTest(APITestCase):
    
    def setUp(self):        
        """
        Set up for the Acknowledgement Test

        Objects created:
        -User
        -Customer
        -Supplier
        -Address
        -product
        -2 fabrics

        After Creating all the needed objects for the Acknowledgement, 
        test that all the objects have been made.
        """
        super(ShippingResourceTest, self).setUp()
        
        self.ct = ContentType(app_label="shipping")
        self.ct.save()

        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, '*****@*****.**', self.password)
        self.user.save()
        
        p = Permission(content_type=self.ct, codename="change_shipping")
        p.save()
        p2 = Permission(content_type=self.ct, codename="add_shipping")
        p2.save()
        self.user.user_permissions.add(p)
        self.user.user_permissions.add(p2)
        
        self.user.save()

        self.setup_client()

        
        #Create supplier, customer and addrss
        self.customer = Customer(**base_customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()
        
        #Create project
        self.project = Project.objects.create(codename="Ladawan")
        
        #Create phase
        self.phase = Phase.objects.create(description="Phase 1/6", project=self.project)
        
        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()
        self.fabric = Fabric.create(**base_fabric)
        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)
        
        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        self.ack = Acknowledgement(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()
        
        #Create an item
        item_data = {'id': 1,
                     'quantity': 1,
                     'is_custom_size': True,
                     'width': 1500,
                     "fabric": {"id":1}}
        self.item = AckItem.create(acknowledgement=self.ack, **item_data)
        
        #Create an item
        item_data = {'id': 1,
                     'quantity': 2,
                     'is_custom_size': True,
                     'width': 1500,
                     "fabric": {"id":1}}
        self.item2 = AckItem.create(acknowledgement=self.ack, **item_data)
    
    def create_shipping(self):
        #create a shipping item
        self.shipping = Shipping.create(acknowledgement={'id': 1}, customer={'id': 1},
                                        user=self.user, delivery_date=base_delivery_date,
                                        items=[{'id': 1}, {'id': 2}])
        self.shipping.save()
        
    def get_credentials(self):
        return self.user#self.create_basic(username=self.username, password=self.password)
    
    def setup_client(self):
        # Login the Client

        # APIClient
        #self.client = APIClient(enforce_csrf_checks=False)
        #self.client.login(username=self.username, password=self.password)
        self.client.force_authenticate(self.user)

    def test_get_list(self):
        """
        Tests getting a list of objects via GET
        """
        self.skipTest('')
        #Create a shipping to retrieve
        self.create_shipping()
        
        resp = self.client.get('/api/v1/shipping/', format='json', authentication=self.get_credentials())
        self.assertEqual(resp.status_code, 200)
        
        #Validate the resources returned
        resp_obj = resp.data
        self.assertEqual(len(resp_obj['objects']), 1)
        
    def test_get(self):
        """
        Tests getting an object via GET
        """
        self.skipTest('')
        self.create_shipping()
        
        #Test the resp
        resp = self.client.get('/api/v1/shipping/1/', format='json', 
                                   authentication=self.get_credentials())
        self.assertEqual(resp.status_code, 200)
        
        #Validate the object
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertIn("customer", obj)
        self.assertEqual(obj['customer']['id'], 1)
    
    def test_post_project_shipping(self):
        """
        Test creating a project packing list via POST
        """
        data = {'project': {'id': 1},
                'customer': {'id': 1},
                'phase': {'id': 1},
                'items': [
                    {'description': 'TK 1/2'}
                ]}
                
        resp = self.client.post('/api/v1/shipping/', format='json', data=data)
        
        # Test client response
        self.assertEqual(resp.status_code, 201, msg=resp)
        
    def test_post_with_two_item(self):
        """
        Tests creating a resource via POST
        """
        #Validate the resp and obj creation
        self.assertEqual(Shipping.objects.count(), 0)
        shipping_data={'acknowledgement': {'id': 1},
                       'customer': {'id': 1},
                       'delivery_date': base_delivery_date,
                       'items': [{'item': {'id': 1},
                                  'description':'test1',
                                  'quantity': 1},
                                 {'item':{'id': 2}}]}
        resp = self.client.post('/api/v1/shipping/', data=shipping_data, format='json')

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Shipping.objects.count(), 1)
        
        #validate the object returned
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertIn('customer', obj)
        self.assertEqual(obj['customer']['id'], 1)
        self.assertIn('last_modified', obj)
        self.assertIn('time_created', obj)
        self.assertEqual(len(obj['items']), 2)
        item1 = obj['items'][0]
        
        #Validate resource in the database
        shipping = Shipping.objects.get(pk=1)
        self.assertEqual(shipping.id, 1)
        self.assertEqual(shipping.customer.id, 1)
        self.assertEqual(shipping.items.count(), 2)
        
    def test_post_with_one_item(self):
        """
        Tests creating a resource via POST
        """
        #Validate the resp and obj creation
        self.assertEqual(Shipping.objects.count(), 0)
        shipping_data={'acknowledgement': {'id': 1},
                       'customer': {'id': 1},
                       'delivery_date': base_delivery_date,
                       'items': [{'item': {'id': 1},
                                  'description':'test1',
                                  'quantity': 1}]}
        resp = self.client.post('/api/v1/shipping/', data=shipping_data, format='json')

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Shipping.objects.count(), 1)
        
        #validate the object returned
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertIn('customer', obj)
        self.assertEqual(obj['customer']['id'], 1)
        self.assertIn('last_modified', obj)
        self.assertIn('time_created', obj)
        self.assertEqual(len(obj['items']), 1)
        item1 = obj['items'][0]
        
        #Validate resource in the database
        shipping = Shipping.objects.get(pk=1)
        self.assertEqual(shipping.id, 1)
        self.assertEqual(shipping.customer.id, 1)
        self.assertEqual(shipping.items.count(), 1)
                
    def test_put(self):
        """
        Tests updating a resource via PUT
        """
        self.skipTest('')
        self.create_shipping()
        self.assertEqual(Shipping.objects.count(), 1)
        resp = self.client.put('/api/v1/shipping/1/', format='json',
                                   authentication=self.get_credentials(),
                                   data={'delivery_date':base_delivery_date, 'acknowledgement': {'id': 1}})
        self.assertEqual(resp.status_code, 200, msg=resp)
        self.assertEqual(Shipping.objects.count(), 1)
        
        #Validate the obj
        obj = resp.data
        self.assertEqual(obj['id'], 1)
        self.assertEqual(obj['customer']['id'], 1)
        self.assertEqual(obj['comments'], 'test')
        
    def test_delete(self):
        """
        Tests deleting a resource via DELETE
        """
        self.skipTest('')
        self.create_shipping()
        self.assertEqual(Shipping.objects.count(), 1)
        resp = self.client.delete('/api/v1/shipping/1/', format='json',
                                      authentication=self.get_credentials())
        self.assertEqual(resp.status_code, 204)
        self.assertEqual(Shipping.objects.count(), 0)
        
        
            
        
        
        
Esempio n. 28
0
    def setUp(self):        
        """
        Set up for the Acknowledgement Test

        Objects created:
        -User
        -Customer
        -Supplier
        -Address
        -product
        -2 fabrics

        After Creating all the needed objects for the Acknowledgement, 
        test that all the objects have been made.
        """
        super(ShippingResourceTest, self).setUp()
        
        self.ct = ContentType(app_label="shipping")
        self.ct.save()

        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, '*****@*****.**', self.password)
        self.user.save()
        
        p = Permission(content_type=self.ct, codename="change_shipping")
        p.save()
        p2 = Permission(content_type=self.ct, codename="add_shipping")
        p2.save()
        self.user.user_permissions.add(p)
        self.user.user_permissions.add(p2)
        
        self.user.save()

        self.setup_client()

        
        #Create supplier, customer and addrss
        self.customer = Customer(**base_customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()
        
        #Create project
        self.project = Project.objects.create(codename="Ladawan")
        
        #Create phase
        self.phase = Phase.objects.create(description="Phase 1/6", project=self.project)
        
        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()
        self.fabric = Fabric.create(**base_fabric)
        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)
        
        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        self.ack = Acknowledgement(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()
        
        #Create an item
        item_data = {'id': 1,
                     'quantity': 1,
                     'is_custom_size': True,
                     'width': 1500,
                     "fabric": {"id":1}}
        self.item = AckItem.create(acknowledgement=self.ack, **item_data)
        
        #Create an item
        item_data = {'id': 1,
                     'quantity': 2,
                     'is_custom_size': True,
                     'width': 1500,
                     "fabric": {"id":1}}
        self.item2 = AckItem.create(acknowledgement=self.ack, **item_data)
Esempio n. 29
0
class GroupResourceTest(ResourceTestCase):
    def setUp(self):
        """
        Set up the environment for the test cases
        """
        super(GroupResourceTest, self).setUp()
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_superuser('tester', '*****@*****.**', 'test')
        self.user.user_permissions.add(Permission.objects.get(codename="add_user"))
        self.api_client.client.login(username='******', password='******')
        
        #Create a group
        self.group = Group(name="God")
        self.group.save()
        
        #Create a permission
        self.ct = ContentType(name='test')
        self.ct.save()
        self.permission = Permission(name='Test', codename='test',
                                     content_type=self.ct)
        self.permission.save()
        
        self.group.permissions.add(self.permission)
        
    def test_get_list(self):
        """
        Tests getting a list of groups via GET
        """
        #Tests the resp
        resp = self.api_client.get('/api/v1/group/')
        self.assertHttpOK(resp)
        
    def test_get(self):
        """
        Tests getting a group via GET
        """
        #Tests the resp
        resp = self.api_client.get('/api/v1/group/1/')
        self.assertHttpOK(resp)
        
        #Tests the return data
        group = self.deserialize(resp)
        self.assertEqual(group['id'], 1)
        self.assertEqual(group['name'], 'God')
        self.assertIn('permissions', group)
        self.assertEqual(len(group['permissions']), 1)
        
    def test_post(self):
        """
        Test creating a new group via POST
        """
        #Test the api and the respose
        self.assertEqual(Group.objects.count(), 1)
        resp = self.api_client.post('/api/v1/group/', format='json',
                                    data={'name': 'Boss',
                                          'group': 'Boss',
                                          'permissions': [{'id': 1}]})
        self.assertHttpCreated(resp)
        self.assertEqual(Group.objects.count(), 2)
        self.assertEqual(Group.objects.order_by('-id').all()[0].permissions.count(), 1)
        
        #Tests the data to be returned
        self.assertEqual(group['id'], 2)
        self.assertEqual(group['name'], 'Boss')
        self.assertIn('permissions', group)
        self.assertEqual(len(group['permissions']), 1)
        self.assertEqual(group['permissions'][0]['name'], Permission.objects.get(pk=1).name)
Esempio n. 30
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")
Esempio n. 31
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"))
Esempio n. 32
0
    def setUp(self):
        """
        Set up for the Estimate Test

        Objects created:
        -User
        -Customer
        -Supplier
        -Address
        -product
        -2 fabrics

        After Creating all the needed objects for the Estimate, 
        test that all the objects have been made.
        """
        super(EstimateResourceTest, self).setUp()

        # Set Base URL
        self.base_url = '{0}'.format('/api/v1/estimate/')

        self.ct = ContentType(app_label="estimates")
        self.ct.save()
        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, '*****@*****.**',
                                             self.password)
        p = Permission(content_type=self.ct, codename="change_estimate")
        p.save()
        p2 = Permission(content_type=self.ct, codename="add_estimate")
        p2.save()
        self.user.user_permissions.add(p)
        self.user.user_permissions.add(p2)

        self.user.save()

        self.setup_client()

        #Create supplier, customer and addrss
        customer = copy.deepcopy(base_customer)
        del customer['id']
        self.customer = Customer(**customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()

        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()

        #Create custom product
        self.custom_product = Product()
        self.custom_product.id = 10436
        self.custom_product.save()

        self.fabric = Fabric.create(**base_fabric)
        self.fabric.quantity = 26
        self.fabric.save()

        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)

        #Create custom product
        self.custom_product = Product.create(self.user,
                                             description="Custom Custom",
                                             id=10436,
                                             width=0,
                                             depth=0,
                                             height=0,
                                             price=0,
                                             wholesale_price=0,
                                             retail_price=0)
        self.custom_product.id = 10436
        self.custom_product.save()

        self.image = S3Object(key='test', bucket='test')
        self.image.save()

        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        del ack_data['project']
        self.ack = Estimate(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()

        #Create an item
        item_data = {
            'id': 1,
            'quantity': 1,
            'is_custom_size': True,
            'width': 1500,
            "fabric": {
                "id": 1
            }
        }
        self.item = Item.create(estimate=self.ack, **item_data)
        item_data = {
            'is_custom': True,
            'description': 'F-04 Sofa',
            'quantity': 3
        }
        self.item2 = Item.create(estimate=self.ack, **item_data)

        #Create fake S3Objects to test files attached to acknowledgements
        self.file1 = S3Object(key='test1', bucket='test')
        self.file2 = S3Object(key='test2', bucket='test')
        self.file1.save()
        self.file2.save()
Esempio n. 33
0
class EstimateResourceTest(APITestCase):
    """"
    This tests the api acknowledgements:
    
    GET list:
    -get a list of objects
    -objects have items and items have pillows
    
    GET:
    -the acknowledgement has delivery date, order date
    customer, status, total, vat, employee, discount
    -the acknowledgement has a list of items.
    -The items have pillows and fabrics
    -pillows have fabrics
    -the items has dimensions, pillows, fabric, comments
    price per item
    
    POST:
    -create an acknowledgement that has delivery date, order date
    customer, status, total, vat, employee, discount, items
    -the items should have fabrics and pillows where appropriate
    """
    
    def setUp(self):
        """
        Set up for the Estimate Test

        Objects created:
        -User
        -Customer
        -Supplier
        -Address
        -product
        -2 fabrics

        After Creating all the needed objects for the Estimate, 
        test that all the objects have been made.
        """
        super(EstimateResourceTest, self).setUp()

        self.ct = ContentType(app_label="estimates")
        self.ct.save()
        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, '*****@*****.**', self.password)
        p = Permission(content_type=self.ct, codename="change_estimate")
        p.save()
        p2 = Permission(content_type=self.ct, codename="add_estimate")
        p2.save()
        self.user.user_permissions.add(p)
        self.user.user_permissions.add(p2)
        
        self.user.save()
        
        #Create supplier, customer and addrss
        customer = copy.deepcopy(base_customer)
        del customer['id']
        self.customer = Customer(**customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()
        
        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()
        
        #Create custom product
        self.custom_product = Product()
        self.custom_product.id = 10436
        self.custom_product.save()
        
        self.fabric = Fabric.create(**base_fabric)
        self.fabric.quantity = 26
        self.fabric.save()
        
        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)
        
        #Create custom product
        self.custom_product = Product.create(self.user, description="Custom Custom", id=10436,
                                             width=0, depth=0, height=0,
                                             price=0, wholesale_price=0, retail_price=0)
        self.custom_product.id = 10436
        self.custom_product.save()
        
        self.image = S3Object(key='test', bucket='test')
        self.image.save()
        
        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        del ack_data['project']
        self.ack = Estimate(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()
        
        #Create an item
        item_data = {'id': 1,
                     'quantity': 1,
                     'is_custom_size': True,
                     'width': 1500,
                     "fabric": {"id":1}}
        self.item = Item.create(estimate=self.ack, **item_data)
        item_data = {'is_custom': True,
                     'description': 'F-04 Sofa',
                     'quantity': 3}
        self.item2 = Item.create(estimate=self.ack, **item_data)
        self.client.login(username="******", password="******")
        
        #Create fake S3Objects to test files attached to acknowledgements
        self.file1 = S3Object(key='test1', bucket='test')
        self.file2 = S3Object(key='test2', bucket='test')
        self.file1.save()
        self.file2.save()
        
    def get_credentials(self):
        return None#self.create_basic(username=self.username, password=self.password)
        
            
    def test_get_list(self):
        """
        Tests getting the list of acknowledgements
        """
        #Get and verify the resp
        resp = self.client.get('/api/v1/estimate/')
        self.assertEqual(resp.status_code, 200, msg=resp)

        #Verify the data sent
        resp_obj = resp.data
        self.assertIsNotNone(resp_obj['results'])
        self.assertEqual(len(resp_obj['results']), 1)
        self.assertEqual(len(resp_obj['results'][0]['items']), 2)
    
    def test_get(self):
        """
        Tests getting the acknowledgement
        """
        #Get and verify the resp
        resp = self.client.get('/api/v1/estimate/1/')
        self.assertEqual(resp.status_code, 200, msg=resp)

        #Verify the data sent
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 1)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['po_id'], '123-213-231')
        self.assertEqual(dateutil.parser.parse(ack['delivery_date']), base_delivery_date)
        self.assertEqual(ack['vat'], 0)
        self.assertEqual(Decimal(ack['total']), Decimal(0))
    
    def xtest_post_dr_vs_pci(self):
        """
        Test POSTING ack with company as 'Dellarobbia Thailand' vs 'Pacific Carpet'
        """
        logger.debug("\n\n Testing creating acknowledgement with diferring companies\n")
        ack1_data = copy.deepcopy(base_ack)
        ack1_data['company'] = 'Dellarobbia Thailand'
        ack
        
    def test_post_with_discount(self):
        """
        Testing POSTing data to the api
        """
        
        logger.debug("\n\n Testing creating acknowledgement with a discount \n")
        #Apply a discount to the customer
        self.customer.discount = 50
        self.customer.save()
        
        modified_data = copy.deepcopy(base_ack)
        modified_data['items'][-1]['fabric'] = {'id': 1,
                                                'image': {'id': 1}}
        modified_data['items'][-1]['fabric_quantity'] = 8
        modified_data['files'] = [{'id': 1}, {'id': 2}]
        
        #POST and verify the response
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/',  
                                data=modified_data,
                                format='json')

        #Verify that http response is appropriate
        self.assertEqual(resp.status_code, 201, msg=resp)
        
        #Verify that an acknowledgement is created in the system
        self.assertEqual(Estimate.objects.count(), 2)
        
        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(ack['vat'], 0)
        self.assertEqual(Decimal(ack['total']), Decimal(158500))
        self.assertEqual(len(ack['items']), 3)
        self.assertIn('project', ack)
        self.assertEqual(ack['project']['id'], 1)
        self.assertEqual(ack['project']['codename'], 'Ladawan1')
        #self.assertIsInstance(ack['files'], list)
        #self.assertEqual(len(ack['files']), 2)
        
        #Test standard sized item 
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(item1['quantity'], 2)
        self.assertFalse(item1['is_custom_size'])
        self.assertFalse(item1['is_custom_item'])
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item1['total']), Decimal(200000))
        
        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(item2['quantity'], 1)
        self.assertTrue(item2['is_custom_size'])
        self.assertFalse(item2['is_custom_item'])
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal(117000))
        self.assertEqual(Decimal(item2['total']), Decimal(117000))
        
        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertTrue(item3['is_custom_item'])
        self.assertEqual(item3['quantity'], 1)
        self.assertEqual(Decimal(item3['unit_price']), 0)
        self.assertEqual(item3['fabric']['id'], 1)
        
        #Tests links to document
        """
        self.assertIsNotNone(ack['pdf'])
        self.assertIsNotNone(ack['pdf']['acknowledgement'])
        self.assertIsNotNone(ack['pdf']['production'])
        self.assertIsNotNone(ack['pdf']['confirmation'])
        """
        
        #Tests the acknowledgement in the database
        root_ack = Estimate.objects.get(pk=2)
        logger.debug(root_ack.project)
        self.assertEqual(root_ack.id, 2)
        self.assertEqual(root_ack.items.count(), 3)
        self.assertIsInstance(root_ack.project, Project)
        self.assertEqual(root_ack.project.id, 1)
        self.assertEqual(root_ack.project.codename, "Ladawan1")
        root_ack_items = root_ack.items.all()
        item1 = root_ack_items[0]
        item2 = root_ack_items[1]
        item3 = root_ack_items[2]
        self.assertEqual(item1.estimate.id, 2)
        self.assertEqual(item1.description, 'Test Sofa Max')
        self.assertEqual(item1.quantity, 2)
        self.assertEqual(item1.width, 1000)
        self.assertEqual(item1.height, 320)
        self.assertEqual(item1.depth, 760)
        self.assertFalse(item1.is_custom_item)
        self.assertFalse(item1.is_custom_size)
        self.assertEqual(item2.estimate.id, 2)
        self.assertEqual(item2.description, 'High Gloss Table')
        self.assertEqual(item2.width, 1500)
        self.assertEqual(item2.height, 320)
        self.assertEqual(item2.depth, 760)
        self.assertTrue(item2.is_custom_size)
        self.assertFalse(item2.is_custom_item)
        self.assertEqual(item3.estimate.id, 2)
        self.assertEqual(item3.description, 'test custom item')
        self.assertEqual(item3.width, 1)
        self.assertTrue(item3.is_custom_item)
        self.assertEqual(item3.quantity, 1)
        
        #Tests files attached to acknowledgements
        """
        self.assertEqual(root_ack.files.all().count(), 2)
        file1 = root_ack.files.all()[0]
        self.assertEqual(file1.id, 1)
        file2 = root_ack.files.all()[1]
        self.assertEqual(file2.id, 2)
        
        #Test Fabric Log
        self.assertEqual(Log.objects.filter(acknowledgement_id=root_ack.id).count(), 1)
        log = Log.objects.get(acknowledgement_id=root_ack.id)
        self.assertEqual(log.quantity, Decimal('33'))
        self.assertEqual(log.action, 'RESERVE')
        self.assertEqual(log.acknowledgement_id, '2')
        self.assertEqual(log.message, 'Reserve 33m of Pattern: Max, Col: charcoal for Ack#2')
        self.assertEqual(Fabric.objects.get(id=1).quantity, Decimal('-7'))
        """
        
    def test_post_with_custom_image(self):
        """
        Testing POSTing data to the api with custom item with custom image
        """
        
        logger.debug("\n\n Testing creating acknowledgement with a custom image \n")
        #Apply a discount to the customer
        ack = copy.deepcopy(base_ack)
        ack['items'][2]['image'] = {'id': 1}
                
        #POST and verify the response
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/',  
                                data=ack,
                                format='json')

        #Verify that http response is appropriate
        self.assertEqual(resp.status_code, 201, msg=resp)
        
        #Verify that an acknowledgement is created in the system
        self.assertEqual(Estimate.objects.count(), 2)
        
        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(ack['vat'], 0)
        self.assertEqual(Decimal(ack['total']), Decimal(317000))
        self.assertEqual(len(ack['items']), 3)
        self.assertIn('project', ack)
        self.assertEqual(ack['project']['id'], 1)
        self.assertEqual(ack['project']['codename'], 'Ladawan1')
        
        #Test standard sized item 
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(item1['quantity'], 2)
        self.assertFalse(item1['is_custom_size'])
        self.assertFalse(item1['is_custom_item'])
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item1['total']), Decimal(200000))
        
        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(item2['quantity'], 1)
        self.assertTrue(item2['is_custom_size'])
        self.assertFalse(item2['is_custom_item'])
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal(117000))
        self.assertEqual(Decimal(item2['total']), Decimal(117000))
        
        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertTrue(item3['is_custom_item'])
        self.assertEqual(item3['quantity'], 1)
        self.assertEqual(Decimal(item3['unit_price']), 0)
        self.assertIsNotNone(item3['image'])
        self.assertIn('url', item3['image'])
        
        
        #Tests links to document
        self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])
        #logger.debug(ack['pdf']['confirmation'])
        #print "\n\n\n"
        
        #Tests the acknowledgement in the database
        root_ack = Estimate.objects.get(pk=2)
        logger.debug(root_ack.project)
        self.assertEqual(root_ack.id, 2)
        self.assertEqual(root_ack.items.count(), 3)
        self.assertIsInstance(root_ack.project, Project)
        self.assertEqual(root_ack.project.id, 1)
        self.assertEqual(root_ack.project.codename, "Ladawan1")
        root_ack_items = root_ack.items.all()
        item1 = root_ack_items[0]
        item2 = root_ack_items[1]
        item3 = root_ack_items[2]
        self.assertEqual(item1.estimate.id, 2)
        self.assertEqual(item1.description, 'Test Sofa Max')
        self.assertEqual(item1.quantity, 2)
        self.assertEqual(item1.width, 1000)
        self.assertEqual(item1.height, 320)
        self.assertEqual(item1.depth, 760)
        self.assertFalse(item1.is_custom_item)
        self.assertFalse(item1.is_custom_size)
        self.assertEqual(item2.estimate.id, 2)
        self.assertEqual(item2.description, 'High Gloss Table')
        self.assertEqual(item2.width, 1500)
        self.assertEqual(item2.height, 320)
        self.assertEqual(item2.depth, 760)
        self.assertTrue(item2.is_custom_size)
        self.assertFalse(item2.is_custom_item)
        self.assertEqual(item3.estimate.id, 2)
        self.assertEqual(item3.description, 'test custom item')
        self.assertEqual(item3.width, 1)
        self.assertTrue(item3.is_custom_item)
        self.assertEqual(item3.quantity, 1)
    
    def test_post_without_vat(self):
        """
        Testing POSTing data to the api
        """
        logger.debug("\n\n Testing creating acknowledgement without vat \n")
        
        #POST and verify the response
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/', format='json',
                                    data=base_ack,
                                    authentication=self.get_credentials())

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Estimate.objects.count(), 2)
        
        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(ack['vat'], 0)
        self.assertEqual(Decimal(ack['total']), Decimal('317000'))
        self.assertEqual(len(ack['items']), 3)
        self.assertIn('project', ack)
        self.assertEqual(ack['project']['id'], 1)
        self.assertEqual(ack['project']['codename'], 'Ladawan1')
        
        #Test standard sized item 
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(item1['quantity'], 2)
        self.assertFalse(item1['is_custom_size'])
        self.assertFalse(item1['is_custom_item'])
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item1['total']), Decimal(200000))
        
        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(item2['quantity'], 1)
        self.assertTrue(item2['is_custom_size'])
        self.assertFalse(item2['is_custom_item'])
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal(117000))
        self.assertEqual(Decimal(item2['total']), Decimal(117000))
        
        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertTrue(item3['is_custom_item'])
        self.assertEqual(item3['quantity'], 1)
        self.assertEqual(Decimal(item3['unit_price']), 0)
        
        #Tests links to document
        self.assertIsNotNone(ack['pdf'])
        #?self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])
    
    def test_post_with_vat(self):
        """
        Testing POSTing data to the api if there
        is vat
        """
        logger.debug("\n\n Testing creating acknowledgement with vat \n")
        
        #Altering replication of base ack data
        ack_data = base_ack.copy()
        ack_data['vat'] = 7
        
        #Verifying current number of acknowledgements in database
        self.assertEqual(Estimate.objects.count(), 1)
        
        resp = self.client.post('/api/v1/estimate/', format='json',
                                    data=ack_data,
                                    authentication=self.get_credentials())
    
        self.assertEqual(resp.status_code, 201, msg=resp)
        
        self.assertEqual(Estimate.objects.count(), 2)
        
        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(ack['vat'], 7)
        self.assertEqual(Decimal(ack['total']), Decimal(339190.00))
        self.assertEqual(len(ack['items']), 3)
        self.assertIn('project', ack)
        self.assertEqual(ack['project']['id'], 1)
        self.assertEqual(ack['project']['codename'], 'Ladawan1')
        
        #Test standard sized item 
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(item1['quantity'], 2)
        self.assertFalse(item1['is_custom_size'])
        self.assertFalse(item1['is_custom_item'])
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item1['total']), Decimal(200000))
        
        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(item2['quantity'], 1)
        self.assertTrue(item2['is_custom_size'])
        self.assertFalse(item2['is_custom_item'])
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal(117000))
        self.assertEqual(Decimal(item2['total']), Decimal(117000))
        
        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertTrue(item3['is_custom_item'])
        self.assertEqual(item3['quantity'], 1)
        self.assertEqual(Decimal(item3['unit_price']), 0)
        
        #Tests links to document
        self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])
    
    def test_post_with_vat_and_discount(self):
        """
        Testing POSTing data to the api if there
        is vat
        """
        logger.debug("\n\n Testing creating acknowledgement with a discount and vat \n")
        
        #Set customer discount
        self.customer.discount = 50
        self.customer.save()
        
        #POST and verify the response
        ack_data = base_ack.copy()
        ack_data['vat'] = 7
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/', format='json',
                                    data=ack_data,
                                    authentication=self.get_credentials())
        

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Estimate.objects.count(), 2)
        
        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(ack['vat'], 7)
        self.assertEqual(Decimal(ack['total']), Decimal('169595.000'))
        self.assertEqual(len(ack['items']), 3)
        
        #Test standard sized item 
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(item1['quantity'], 2)
        self.assertFalse(item1['is_custom_size'])
        self.assertFalse(item1['is_custom_item'])
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal(100000))
        self.assertEqual(Decimal(item1['total']), Decimal(200000))
        
        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(item2['quantity'], 1)
        self.assertTrue(item2['is_custom_size'])
        self.assertFalse(item2['is_custom_item'])
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal(117000))
        self.assertEqual(Decimal(item2['total']), Decimal(117000))
        
        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertTrue(item3['is_custom_item'])
        self.assertEqual(item3['quantity'], 1)
        self.assertEqual(Decimal(item3['unit_price']), 0)
        
        #Tests links to document
        self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])
        
    def test_post_with_custom_price(self):
        """
        Test creating a custom price for all three item types
        """
        logger.debug("\n\n Testing creating acknowledgement with custom prices for all items \n")
                
        #POST and verify the response
        ack_data = copy.deepcopy(base_ack)
        ack_data['items'][0]['custom_price'] = 100
        ack_data['items'][1]['custom_price'] = 200
        ack_data['items'][2]['custom_price'] = 300

        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/', format='json',
                                    data=ack_data,
                                    authentication=self.get_credentials())
        

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Estimate.objects.count(), 2)
        
        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(ack['vat'], 0)
        self.assertEqual(Decimal(ack['total']), Decimal('700.00'))
        self.assertEqual(len(ack['items']), 3)
        
        #Test standard sized item 
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(item1['quantity'], 2)
        self.assertFalse(item1['is_custom_size'])
        self.assertFalse(item1['is_custom_item'])
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertEqual(item1['fabric']['id'], 1)
        self.assertEqual(len(item1['pillows']), 4)
        self.assertEqual(Decimal(item1['unit_price']), Decimal('100'))
        self.assertEqual(Decimal(item1['total']), Decimal('200'))
        
        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(item2['quantity'], 1)
        self.assertTrue(item2['is_custom_size'])
        self.assertFalse(item2['is_custom_item'])
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal('200'))
        self.assertEqual(Decimal(item2['total']), Decimal('200'))
        
        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertTrue(item3['is_custom_item'])
        self.assertEqual(item3['quantity'], 1)
        self.assertEqual(Decimal(item3['unit_price']), Decimal('300'))
        
        #Tests links to document
        self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])
        
    def test_post_where_first_item_has_no_fabric(self):
        """
        Test creating a custom price for all three item types
        """
        logger.debug("\n\n Testing creating acknowledgement with custom prices for all items \n")
                
        #POST and verify the response
        ack_data = copy.deepcopy(base_ack)
        del ack_data['items'][0]['fabric']
        del ack_data['items'][0]['pillows'][0]['fabric']

        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.post('/api/v1/estimate/', format='json',
                                    data=ack_data,
                                    authentication=self.get_credentials())
        

        self.assertEqual(resp.status_code, 201, msg=resp)
        self.assertEqual(Estimate.objects.count(), 2)
        
        #Verify the resulting acknowledgement
        #that is returned from the post data
        ack = resp.data
        self.assertIsNotNone(ack)
        self.assertEqual(ack['id'], 2)
        self.assertEqual(ack['customer']['id'], 1)
        self.assertEqual(ack['employee']['id'], 1)
        self.assertEqual(ack['vat'], 0)
        self.assertEqual(Decimal(ack['total']), Decimal('317000'))
        self.assertEqual(len(ack['items']), 3)
        
        #Test standard sized item 
        item1 = ack['items'][0]
        self.assertEqual(item1['id'], 3)
        self.assertEqual(item1['description'], 'Test Sofa Max')
        self.assertEqual(item1['quantity'], 2)
        self.assertFalse(item1['is_custom_size'])
        self.assertFalse(item1['is_custom_item'])
        self.assertEqual(item1['width'], 1000)
        self.assertEqual(item1['height'], 320)
        self.assertEqual(item1['depth'], 760)
        self.assertIsNone(item1['fabric'])
        self.assertEqual(len(item1['pillows']), 5)
        self.assertEqual(Decimal(item1['unit_price']), Decimal('100000'))
        self.assertEqual(Decimal(item1['total']), Decimal('200000'))
        
        #Test custom sized item
        item2 = ack['items'][1]
        self.assertEqual(item2['id'], 4)
        self.assertEqual(item2['description'], 'High Gloss Table')
        self.assertEqual(item2['quantity'], 1)
        self.assertTrue(item2['is_custom_size'])
        self.assertFalse(item2['is_custom_item'])
        self.assertEqual(item2['width'], 1500)
        self.assertEqual(item2['height'], 320)
        self.assertEqual(item2['depth'], 760)
        self.assertEqual(item2['fabric']['id'], 1)
        self.assertEqual(Decimal(item2['unit_price']), Decimal('117000'))
        self.assertEqual(Decimal(item2['total']), Decimal('117000'))
        
        #Test custom item with width
        item3 = ack['items'][2]
        self.assertEqual(item3['width'], 1)
        self.assertEqual(item3['description'], 'test custom item')
        self.assertTrue(item3['is_custom_item'])
        self.assertEqual(item3['quantity'], 1)
        
        #Tests links to document
        self.assertIsNotNone(ack['pdf'])
        #self.assertIsNotNone(ack['pdf']['acknowledgement'])
        #self.assertIsNotNone(ack['pdf']['production'])
        #self.assertIsNotNone(ack['pdf']['confirmation'])
    
    @unittest.skip('currently not allowed')    
    def test_put(self):
        """
        Test making a PUT call
        """
        logger.debug("\n\n Testing updating via put \n")
        
        ack_data = base_ack.copy()
        ack_data['items'][0]['id'] = 1
        del ack_data['items'][0]['pillows'][-1]
        ack_data['items'][1]['id'] = 2
        ack_data['items'][1]['description'] = 'F-04 Sofa'
        ack_data['items'][1]['is_custom_item'] = True
        del ack_data['items'][2]
        ack_data['delivery_date'] = datetime.now()
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.put('/api/v1/estimate/1/', 
                                   format='json',
                                   data=ack_data,
                                   authentication=self.get_credentials())
        logger.debug(resp)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(Estimate.objects.count(), 1)
        
        #Validate the change
        ack = resp.data
        #self.assertEqual(dateutil.parser.parse(ack['delivery_date']), ack_data['delivery_date'])
        logger.debug(ack['items'][0]['pillows'])
        #Tests ack in database
        ack = Estimate.objects.get(pk=1)
        items = ack.items.all()
            
        item1 = items[0]
        self.assertEqual(item1.description, 'Test Sofa Max')
        self.assertEqual(item1.pillows.count(), 3)

        item2 = items[1]
        self.assertEqual(item2.description, 'F-04 Sofa')
        self.assertTrue(item2.is_custom_item)
    
    def test_changing_delivery_date(self):
        """
        Test making a PUT call
        """
        logger.debug("\n\n Testing updating via put \n")
        
        d = datetime.now()
        
        ack_data = base_ack.copy()
       
        ack_data['delivery_date'] = d
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.put('/api/v1/estimate/1/', 
                                   format='json',
                                   data=ack_data,
                                   authentication=self.get_credentials())

        self.assertEqual(resp.status_code, 200, msg=resp)
        
        ack = resp.data
        #logger.debug(ack['delivery_date'])
        #d1 = datetime.strptime(ack['delivery_date'])
        
        #self.assertEqual(d1.date(), d.date())
        
        ack = Estimate.objects.all()[0]
        self.assertEqual(ack.delivery_date.date(), d.date())
        
    #@unittest.skip('ok')    
    def test_delete(self):
        """
        Test making a DELETE call
        
        'Delete' in this model has been overridden so that no acknowledgement 
        is truly deleted. Instead the 'delete' column in the database is marked 
        as true
        """
        self.assertEqual(Estimate.objects.count(), 1)
        resp = self.client.delete('/api/v1/estimate/1/',
                                      authentication=self.get_credentials())

        self.assertEqual(Estimate.objects.count(), 1)
Esempio n. 34
0
    def setUp(self):
        """
        Set up for the Acknowledgement Test

        Objects created:
        -User
        -Customer
        -Supplier
        -Address
        -product
        -2 fabrics

        After Creating all the needed objects for the Acknowledgement, 
        test that all the objects have been made.
        """
        super(ShippingResourceTest, self).setUp()

        self.ct = ContentType(app_label="shipping")
        self.ct.save()

        #Create the user
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, '*****@*****.**',
                                             self.password)
        self.user.save()

        p = Permission(content_type=self.ct, codename="change_shipping")
        p.save()
        p2 = Permission(content_type=self.ct, codename="add_shipping")
        p2.save()
        self.user.user_permissions.add(p)
        self.user.user_permissions.add(p2)

        self.user.save()

        self.setup_client()

        #Create supplier, customer and addrss
        self.customer = Customer(**base_customer)
        self.customer.save()
        self.supplier = Supplier(**base_supplier)
        self.supplier.save()
        self.address = Address(address1="Jiggle", contact=self.customer)
        self.address.save()

        #Create project
        self.project = Project.objects.create(codename="Ladawan")

        #Create phase
        self.phase = Phase.objects.create(description="Phase 1/6",
                                          project=self.project)

        #Create a product to add
        self.product = Product.create(self.user, **base_product)
        self.product.save()
        self.fabric = Fabric.create(**base_fabric)
        f_data = base_fabric.copy()
        f_data["pattern"] = "Stripe"
        self.fabric2 = Fabric.create(**f_data)

        #Create acknowledgement
        ack_data = base_ack.copy()
        del ack_data['customer']
        del ack_data['items']
        del ack_data['employee']
        self.ack = Acknowledgement(**ack_data)
        self.ack.customer = self.customer
        self.ack.employee = self.user
        self.ack.save()

        #Create an item
        item_data = {
            'id': 1,
            'quantity': 1,
            'is_custom_size': True,
            'width': 1500,
            "fabric": {
                "id": 1
            }
        }
        self.item = AckItem.create(acknowledgement=self.ack, **item_data)

        #Create an item
        item_data = {
            'id': 1,
            'quantity': 2,
            'is_custom_size': True,
            'width': 1500,
            "fabric": {
                "id": 1
            }
        }
        self.item2 = AckItem.create(acknowledgement=self.ack, **item_data)
Esempio n. 35
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")
Esempio n. 36
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")
Esempio n. 37
0
class ItemTest(TestCase):
    """
    Tests the PO Item
    """
    def setUp(self):
        """
        Set up dependent objects
        """
        super(ItemTest, 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.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.item = Item(unit_cost=Decimal('13.55'),
                         quantity=Decimal('10'),
                         supply=self.supply)
        self.item.description = self.supply.description
        self.item.purchase_order = self.po
        self.item.save()

    def test_creating_item_with_no_product_with_unit_cost(self):
        """Test creating a item via the serializer where there is no product
        """
        context = {'po': self.po, 'supplier': self.supplier}
        data = {
            'supply': {
                'id': self.supply.id
            },
            'unit_cost': 10,
            'quantity': 5,
            'units': 'yd'
        }

        item_serializer = ItemSerializer(context=context, data=data)
        if item_serializer.is_valid(raise_exception=True):
            item_serializer.save()

        # Verify product is created
        self.assertEqual(
            Product.objects.filter(supply=self.supply,
                                   supplier=self.supplier).count(), 1)

        # Verify item
        resp_data = item_serializer.data

        self.assertEqual(resp_data['description'], 'Pattern: Maxx, Col: Blue')
        self.assertEqual(resp_data['units'], 'yd')
        self.assertEqual(Decimal(resp_data['quantity']), Decimal('5'))
        self.assertEqual(Decimal(resp_data['total']), Decimal('50'))

    def test_creating_item_with_product_with_no_unit_cost(self):
        """Test creating a item via the serializer where there is no product
        """
        Product.objects.create(supply=self.supply,
                               supplier=self.supplier,
                               cost=Decimal('12.11'),
                               purchasing_units="yd")

        context = {'po': self.po, 'supplier': self.supplier}
        data = {'supply': {'id': self.supply.id}, 'quantity': 5, 'units': 'yd'}

        item_serializer = ItemSerializer(context=context, data=data)
        if item_serializer.is_valid(raise_exception=True):
            item_serializer.save()

        # Verify product is created
        self.assertEqual(
            Product.objects.filter(supply=self.supply,
                                   supplier=self.supplier).count(), 1)

        # Verify item
        resp_data = item_serializer.data

        self.assertEqual(resp_data['description'], 'Pattern: Maxx, Col: Blue')
        self.assertEqual(resp_data['units'], 'yd')
        self.assertEqual(Decimal(resp_data['quantity']), Decimal('5'))
        self.assertEqual(Decimal(resp_data['total']), Decimal('60.55'))

    def test_updating_item_without_product(self):

        context = {'po': self.po, 'supplier': self.supplier}
        data = {
            'supply': {
                'id': self.supply.id
            },
            'unit_cost': Decimal('11.22'),
            'quantity': 4,
            'units': 'yd'
        }

        # Verify there is no product
        self.assertEqual(
            Product.objects.filter(supply=self.supply,
                                   supplier=self.supplier).count(), 0)

        # Update item
        item_serializer = ItemSerializer(self.item, context=context, data=data)
        if item_serializer.is_valid(raise_exception=True):
            item_serializer.save()

        # Verify product is created
        self.assertEqual(
            Product.objects.filter(supply=self.supply,
                                   supplier=self.supplier).count(), 1)

        # Verify item
        resp_data = item_serializer.data

        self.assertEqual(resp_data['description'], 'Pattern: Maxx, Col: Blue')
        self.assertEqual(resp_data['units'], 'yd')
        self.assertEqual(Decimal(resp_data['quantity']), Decimal('4'))
        self.assertEqual(Decimal(resp_data['total']), Decimal('44.88'))

    def test_updating_item_with_product(self):
        Product.objects.create(supply=self.supply,
                               supplier=self.supplier,
                               cost=Decimal('12.11'),
                               purchasing_units="yd")

        context = {'po': self.po, 'supplier': self.supplier}
        data = {
            'supply': {
                'id': self.supply.id
            },
            'unit_cost': Decimal('11.22'),
            'quantity': 4,
            'units': 'm'
        }

        # Verify there is a product
        products = Product.objects.filter(supply=self.supply,
                                          supplier=self.supplier)
        self.assertEqual(products.count(), 1)
        self.assertEqual(products[0].cost, Decimal('12.11'))
        self.assertEqual(products[0].purchasing_units, 'yd')

        # Update item
        item_serializer = ItemSerializer(self.item, context=context, data=data)
        if item_serializer.is_valid(raise_exception=True):
            item_serializer.save()

        # Verify product is created
        products2 = Product.objects.filter(supply=self.supply,
                                           supplier=self.supplier)
        self.assertEqual(products2.count(), 1)
        self.assertEqual(products2[0].cost, Decimal('11.22'))
        self.assertEqual(products2[0].purchasing_units, 'm')

        # Verify item
        resp_data = item_serializer.data

        self.assertEqual(resp_data['description'], 'Pattern: Maxx, Col: Blue')
        self.assertEqual(resp_data['units'], 'm')
        self.assertEqual(Decimal(resp_data['quantity']), Decimal('4'))
        self.assertEqual(Decimal(resp_data['total']), Decimal('44.88'))
Esempio n. 38
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()
Esempio n. 39
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'))