2

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?

Scott Greenup
  • 183
  • 1
  • 9
  • I'm wondering if I could make a migration (in code) and apply that (in code), which will apply the migration to the test database during `./manage.py test`? – Scott Greenup Sep 05 '17 at 10:45
  • I've reverted to just testing that the field functions are implemented properly: `deconstruct()`, `to_python()`, `value_to_string()`, `from_db_value()`, and `get_prep_value()`. It seems that creating a migration was easy, but applying the migration in code is likely unsupported at the moment; based upon the code in `./manage.py migrate`. Unless somebody knows extra? – Scott Greenup Sep 05 '17 at 22:37

0 Answers0