How to test if view is able to create a new entity in the db?

Viewed 37

I have to do basic unit testing in order to get my code coverage higher. I do not need to do anything fancy. Just the bare minimum is required. So, in this case if I am able to hit my view successfully, then that is all I need to do. Agile team is nested under Team as you can see in the models.py.

models.py -

class Organization(models.Model):
    orgname = models.CharField(max_length = 100, blank=True)

    def __str__(self):
        return str(self.orgname)

class Team(models.Model):
    teamID = models.AutoField(primary_key=True)
    teamName = models.CharField(max_length = 100, blank=True)
    org = models.ForeignKey(Organization, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.teamName)

class AgileTeam(models.Model):
    agileTeamID = models.AutoField(primary_key=True)
    agileTeamName = models.CharField(max_length = 100, blank=True)
    team = models.ForeignKey(Team,  on_delete=models.CASCADE)

    def __str__(self):
        return str(self.agileTeamName)

views.py -

@csrf_exempt
def newATeam(request):
    if request.method == 'POST':
        param = json.loads(request.body)
        agileteam = param.get('agileteam')
        teamname = param.get('teamname')
        team = Team.objects.get(teamName = teamname)
        AgileTeam.objects.create(agileTeamName=agileteam, team=team)
        return JsonResponse(status = 200, data = {})

urls.py -

path('ajax/newATeam/', views_admin.newATeam, name='ajax_newATeam'),

test_views.py -

class TestViews(TestCase):
@classmethod
    def setUpTestData(self):
        # set-up org
        ORG_NAMES = ['REVCYCSCH', 'DIABLO', 'BROTHERHOOD']
        for org in ORG_NAMES:
            Organization.objects.create(orgname=org)

        # set-up team
        orgModels = Organization.objects.all()
        TEAM_NAMES = ['Blitzkrieg ', 'Hammerheads', 'Mercenaries']
        for i in range(len(TEAM_NAMES)):
            Team.objects.create(teamName=TEAM_NAMES[i], org=orgModels[i])

        # set-up agileteam
        teamModels = Team.objects.all()
        AGILE_TEAM_NAMES = ['Barons', 'Exterminators ', 'Mavericks', 'Renegades', 'Stratosphere', 'Trojans ']
        index = 0
        for team in teamModels:
            for _ in range(2):
                AgileTeam.objects.create(agileTeamName=AGILE_TEAM_NAMES[index], team=team)
                index = index + 1

        self.client = Client()

        def test_newATeam(self):
            params = {'agileteam': 'Barons', 'teamname': 'Blitzkrieg'}
            response = self.client.post(path = '/ajax/newATeam/', data = params, content_type = 'application/json')
            self.assertEqual(response.status_code, 200) 

However, I get this error - Error

Thanks in advance!

2 Answers

There are a few things I would do slightly differently.

In views.py:

@csrf_exempt
def new_agile_team(request):
    if request.method == 'POST':
        if request.META.get('CONTENT_TYPE', '').lower() == 'application/json' and len(request.body) > 0:
            try:
                body_data = json.loads(request.body.decode('utf-8'))
            except Exception as e:
                return HttpResponseBadRequest(json.dumps({
                    'error': 'Invalid request: {0}'.format(str(e))
                 }), content_type="application/json")

        try:
            team = Team.objects.get(teamName = teamname)
            AgileTeam.objects.create(agileTeamName=agileteam, team=team)
        except Team.DoesNotExist as error:
            # Handle error here...

        return JsonResponse(status = 200, data = {})

However, I would strongly recommend using Djago REST framework for this - as you may need to provide only logged in users the ability to create teams, so you'll need to understand @action level permissions on routes, as well as utilising a more RESTful principle.

So... you are sending 'teamName': 'Blitzkrieg', but then you are fetching teamname = param.get('teamname')... of course it wont work, did you even tried to debug it ?

I see so many problems with this code, that I just don't know from where to start, but just for the beginning start using PEP8 + Djagno Coding styles (+ maybe some linter & formatter) and your life will became much more easier.

Related