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:
- https://www.kurup.org/blog/2014/07/21/django-test-models
- https://stackoverflow.com/a/503435/2097917
- https://blog.bixly.com/bixly-how-to-dynamically-adding-models-for-testing-in-django
- http://www.akshayshah.org/post/testing-django-fields/
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?