Home > Mobile >  How to test model labels in Django?
How to test model labels in Django?

Time:10-15

I have the following model.py

from django.db import models

class Url(models.Model):
    short_url = models.CharField(max_length=255)
    original_url = models.CharField(max_length=255)
    clicks = models.IntegerField(default=0)
    created_at = models.DateTimeField('date created', auto_now_add=True)
    updated_at = models.DateTimeField('date updated', auto_now=True)

class Click(models.Model):
    url = models.ForeignKey(Url, on_delete=models.CASCADE, related_name='related_clicks')
    browser = models.CharField(max_length=255)
    platform = models.CharField(max_length=255)
    created_at = models.DateTimeField('date created', auto_now_add=True)
    updated_at = models.DateTimeField('date updated', auto_now=True)

and in the tests/test_models.py

from django.test import TestCase
from heyurl.models import Url, Click
from heyurl.views import short_url


class TestModels(TestCase):
    @classmethod
    def setupTestdata(cls):
        Url.objects.create(short_url='eOlKf', original_url='https://www.google.com', clicks= 2)
    
   #Figuring out how to test each label
    def test_short_url_label(self):
        field_label = Url.objects.get()
        self.assertEqual(field_label, 'short_url')

So basically I would like to know how can I validate my model labels through unit tests in test_models.py What should I use in place of field_label to be able to make use of assertEqual() ?

CodePudding user response:

expected_fields = [...]
model_field_names = [field.name for field in YourModel._meta.get_fields()]

for field_name in expected_fields:
    self.assertTrue(field_name in model_field_names)
  • Related