Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to test model labels in Django?

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() ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading