Test if a class is inherited from another

PythonUnit Testing

Python Problem Overview


This question is more Python related than Django related. I want to test write a test for this function that I am using to get a Django form dynamically with the fields I set.

def quiz_form_factory(question):
    properties = {
        'question': forms.IntegerField(widget=forms.HiddenInput, initial=question.id),
        'answers': forms.ModelChoiceField(queryset=question.answers_set)
    }
    return type('QuizForm', (forms.Form,), properties)

I want to test if, the QuizForm class returned is inherited from forms.Form.

Something like:

self.assertTrue(QuizForm isinheritedfrom forms.Form)  # I know this does not exist

Is there any way to do this?

Python Solutions


Solution 1 - Python

Use issubclass(myclass, parentclass).

In your case:

self.assertTrue( issubclass(QuizForm, forms.Form) )

Solution 2 - Python

Use the built-in issubclass function. e.g.

issubclass(QuizForm, forms.Form)

It returns a bool so you can use it directly in self.assertTrue()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRenne RochaView Question on Stackoverflow
Solution 1 - PythonpajtonView Answer on Stackoverflow
Solution 2 - Pythonbradley.ayersView Answer on Stackoverflow