Table of Contents

    Django code

    Module.py

    
    from django.db import models 
    # Create your models here.
    class Item(models.Model):
    	id =models.AutoField(primary_key=True)
    	name=models.CharField(max_length=250)
    	category=models.CharField(max_length=250)
    	price=models.IntegerField()
    	quantity=models.IntegerField()
    	barcode=models. IntegerField (unique=True)
    

    serializers.py

    
    from rest_framework import serializers
    from .models import Item
    #Create your serializers here.
    class ItemSerializer(serializers.ModelSerializer):
    	class Meta:
    	    model = Item
    	    fields = '__all__'
    

    views.py

    
    from rest_framework import viewsets
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from inventoryapp.serializers import ItemSerializer
    from .models import Item
    from rest_framework import status
    
    # Create your views here
    
    class SortItemsView(APIView):
        def get(self, request):
            items = Item.objects.all().order_by('-price')
            serializer = ItemSerializer(items, many=True)
            return Response(serializer.data)
    
    class QueryItemsView(APIView):
        def get(self, request, category):
            items = Item.objects.filter(category=category)
            serializer = ItemSerializer(items, many=True)
            return Response(serializer.data)
    
    class InventoryItemView(APIView):
        def get(self, request):
            items = Item.objects.all()
            serializer = ItemSerializer(items, many=True)
            return Response(serializer.data)
    
        def post(self, request):
            serializer = ItemSerializer(data=request.data)
            if serializer.is_valid():
                barcode = serializer.validated_data['barcode']
                if Item.objects.filter(barcode=barcode).exists():
                    return Response({'barcode': ['item with this barcode already exists']}, status=status.HTTP_400_BAD_REQUEST)
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
        def delete(self, request, pk):
            try:
                item = Item.objects.get(pk=pk)
            except Item.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
            item.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
    
    

    urls.py

    
    """inventoryapi URL Configuration
    
    The `urlpatterns` list routes URLs to views. For more information please see:
        https://docs.djangoproject.com/en/1.8/topics/http/urls/
    Examples:
    Function views
        1. Add an import:  from my_app import views
        2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
    Class-based views
        1. Add an import:  from other_app.views import Home
        2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
    Including another URLconf
        1. Add an import:  from blog import urls as blog_urls
        2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
    """
    
    from django.urls import include, path
    from django.contrib import admin
    from inventoryapp.views import InventoryItemView, SortItemsView, QueryItemsView
    
    # Add your URLS in respective place.
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('inventory/items/', InventoryItemView.as_view(), name='inventory-item'),
        path('inventory/items/<int:pk>/', InventoryItemView.as_view(), name='inventory-detail'),
        path('items/sort/', SortItemsView.as_view(), name='sort-items'),
        path('items/query/<str:category>/', QueryItemsView.as_view(), name='query-items'),
    ]
    
    

    admin.py

    
    from django.contrib import admin
    from .models import Item
    
    # Register your models here.
    
    admin.site.register(Item)
    

    Run Steps

    
    python3 -m pip install -r requirements.txt
    
    python3 manage.py makemigrations
    
    python3 manage.py migrate --run-syncdb
    
    python3 manage.py runserver
    
    ctrl +c
    
    sh run.sh
    
    ctrl +c
    
    sh install.sh
    
    sh test.sh
    

    tests.py

    
    from django.test import TestCase
    
    # Create your tests here.
    class AppTest(TestCase):
    
        def test_1_inventory_get_success(self):
            res=self.client.get('/inventory/items/')
            print(res.json())
            assert b'[]' in res.content
            assert 200==res.status_code
    
        def test_2_inventory_post_success(self):
            res=self.client.post('/inventory/items/',data={'name':'shirt','category':'top wear','price':700,'discount':20,'quantity':2,'barcode':123456})
            print(res.json())
            assert 'shirt' == res.json()['name']
            assert 201==res.status_code
    
    
        def test_3_inventory_delete_success(self):
            res=self.client.post('/inventory/items/',data={'name':'shirt','category':'top wear','price':700,'discount':20,'quantity':2,'barcode':123456})
            res=self.client.delete('/inventory/items/1/')
            assert 204==res.status_code
    
        
        def test_4_inventory_post_error(self):
            
            res=self.client.post('/inventory/items/',data={'name':'shirt','category':'top wear','price':700,'discount':20,'quantity':2,'barcode':123456})
            res=self.client.post('/inventory/items/',data={'name':'t-shirt','category':'top wear','price':1300,'discount':30,'quantity':2,'barcode':123456})
            print(res.json())
            assert b'inventory with this barcode already exists' in res.content
            assert 400==res.status_code
    
    
        def test_5_inventory_get_sort_success(self):
            res=self.client.post('/inventory/items/',data={'name':'shirt','category':'top wear','price':700,'discount':20,'quantity':2,'barcode':123456})
            res=self.client.post('/inventory/items/',data={'name':'t-shirt','category':'top wear','price':1300,'discount':30,'quantity':2,'barcode':12345687})
            response=self.client.get('/items/sort/')
            print(response.json())
            assert 1300==response.json()[0]['price']
            assert 700==response.json()[1]['price']
            assert 200==response.status_code
    
        def test_6_inventory_get_query_category_success(self):
            res=self.client.post('/inventory/items/',data={'name':'shirt','category':'top wear','price':700,'discount':20,'quantity':2,'barcode':123456})
            res=self.client.post('/inventory/items/',data={'name':'t-shirt','category':'top wear','price':1300,'discount':30,'quantity':2,'barcode':12345687})  
            res=self.client.post('/inventory/items/',data={'name':'shorts','category':'bottom wear','price':300,'discount':5,'quantity':3,'barcode':123455})
            response=self.client.get('/items/query/top%20wear/')
            print(response.json())
            
            assert 'shirt' in response.json()[0]['name']
            assert 't-shirt' in response.json()[1]['name']
            assert 200==response.status_code
            assert len(response.json())==2