Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a class has an attribute?

People also ask

How do you know if a class has an attribute?

We can use hasattr() function to find if a python object obj has a certain attribute or property. hasattr(obj, 'attribute'): The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block.

How do you check if an object has a certain attribute?

If you want to determine whether a given object has a particular attribute then hasattr() method is what you are looking for. The method accepts two arguments, the object and the attribute in string format.

How do I check attributes in python?

To check if an object in python has a given attribute, we can use the hasattr() function. The function accepts the object's name as the first argument 'object' and the name of the attribute as the second argument 'name. ' It returns a boolean value as the function output.

Has attribute in python?

Python hasattr() Function The hasattr() function returns True if the specified object has the specified attribute, otherwise False .


check that

Attribute.GetCustomAttribute(typeof(ScheduleController),
    typeof(SubControllerActionToViewDataAttribute))

isn't null (Assert.IsNotNull or similar)

(the reason I use this rather than IsDefined is that most times I want to validate some properties of the attribute too....)


The same you would normally check for an attribute on a class.

Here's some sample code.

typeof(ScheduleController)
.IsDefined(typeof(SubControllerActionToViewDataAttribute), false);

I think in many cases testing for the existence of an attribute in a unit test is wrong. As I've not used MVC contrib's sub controller functionality I can't comment whether it is appropriate in this case though.


It is also possible to use generics on this:

var type = typeof(SomeType);
var attribute = type.GetCustomAttribute<SomeAttribute>();

This way you do not need another typeof(...), which can make the code cleaner.


I know this thread is really old, but if somebody stumble upon on it you may find fluentassertions project very convenient for doing this kind of assertions.

typeof(MyPresentationModel).Should().BeDecoratedWith<SomeAttribute>();