1

I'm writing some schema tests for django, using django's wrapper of the unittest framework.

I want to check that a field is always going to be DateTimeField, rather than DateField. So I attempted the following:

class TestSuite(TestCase):
    def test_for_correct_datetype(self):
        self.assertTrue(isinstance(Obj.time, models.DateTimeField))

Because previously:

class Obj(models.Model):
    ....
    time = models.DateTimeField()

Note: There were several answers that said to use getattr, and it doesn't work for me either.

How can I make the self.assertTrue() work?

OneRaynyDay
  • 3,658
  • 2
  • 23
  • 56
  • 1
    Hint: if you want to check type, maybe use the [`assertIsInstance` method](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIsInstance) – Ralf Apr 26 '18 at 14:42

1 Answers1

1

You can use get_field method from the Model _meta API:

from django.db import models

class TestSuite(TestCase):
    def test_for_correct_datetype(self):
        self.assertTrue(isinstance(Obj._meta.get_field('time'), models.DateTimeField))
Alasdair
  • 298,606
  • 55
  • 578
  • 516