mardi 5 septembre 2017

How to test a custom field in Django 1.11.1

I've create a custom field in Django

class MyField(models.CharField):
    description = "My awesome field"

    # ...

I want to create a unit-test in which I make a temporary/ephemeral model that uses the field. My goal is to test that the functions like to_python, from_db_value, and validate, are implemented correctly from the view of an actual Model.

I also don't want to have the Model included in the production database. I've looked up a few different means of doing this and they do not work:

These all seem to be outdated. I would like to be able to define the model within an tests.py file (i.e. projectroot/myapp/tests.py) and somehow have the setUp add the model to the database:

class MyModelTest(models.Model):
    myField = MyField()

class MyFieldTestCase(TestCase):
    def setUp():
        # ... do something funky to create the table

    def test_foo(self):
        myModel = MyModel.objects.create(myField="something")
        self.assertEqual(myModel.myField, "something")

Does anyone have a good idea on how I could approach this?

Aucun commentaire:

Enregistrer un commentaire