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 issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.
Two built-in functions isinstance() and issubclass() are used to check inheritances. The function isinstance() returns True if the object is an instance of the class or other classes derived from it. Each and every class in Python inherits from the base class object .
You can compare two objects to determine the relationship, if any, between the classes from which they are created. The IsInstanceOfType method of the System. Type class returns True if the specified class inherits from the current class, or if the current type is an interface supported by the specified class.
In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes. Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class).
Use issubclass(myclass, parentclass).
In your case:
self.assertTrue( issubclass(QuizForm, forms.Form) )
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With