Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django test fixtures and content types

I'm using django's ContentType foreign key in my model, and I'm using it in the fixtures for unit tests.

Therefore, I have to hard-code content_type_id in my fixture, but django sometimes initializes it to a different value and thus my tests fail.

So is there a way to safely predict the content_type_id of the model or any other proper way to handle such situations?

like image 856
dragoon Avatar asked Nov 08 '11 15:11

dragoon


People also ask

What is Django content type?

Django includes a contenttypes application that can track all of the models installed in your Django-powered project, providing a high-level, generic interface for working with your models.

What are Django fixtures?

A fixture is a collection of data that Django knows how to import into a database. The most straightforward way of creating a fixture if you've already got some data is to use the manage.py dumpdata command.

What should I test in Django?

The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.

What is RequestFactory in Django?

The request factory The API for the RequestFactory is a slightly restricted subset of the test client API: It only has access to the HTTP methods get() , post() , put() , delete() , head() , options() , and trace() . These methods accept all the same arguments except for follow .


1 Answers

Use natural keys: https://docs.djangoproject.com/en/dev/topics/serialization/#natural-keys

Most of the documentation refers to how to add the capability to your own models, but ContentType already supports them so just add --natural-foreign to your dumpdata management command:

$ python manage.py dumpdata myapp --indent=4 --natural-foreign
like image 163
Chris Pratt Avatar answered Sep 18 '22 09:09

Chris Pratt