Search code examples
pythonunit-testingpytesthasattr

How can I use pytest to see if a class attribute attribute exists in python?


I'm a tech teacher, trying to learn how to use pytest to create specialty koans for my students to learn python syntax. (If you check a previous question, I have details as to what's going on here.)

I'm familiar with test driven development, but predominantly with JavaScript/jQuery. I'm also less familiar with OOP when it comes to python syntax, and now I have to teach it to my students (best way to learn and all that, apparently).

I'm fairly sure I'm writing my code correctly as the command line tests are working, but I need to use TDD for this to work, as my students don't have access to the command line and must run the code in the browser-based code system.

I've tried using hasattr(), but it's always returning False, even when it shouldn't be, assuming I've used it correctly.

The code for the class is such:

class Dog:
  def __init__(self, name, breed):
    self.name = name
    self.breed = breed

The code for the test is in another file, and looks like this:

from utils.attribute_1 import Dog


def test_Dog():
  assert hasattr(Dog, 'name')

So what I've done above is import the class, Dog, from the file, and set up a test function that should show that I have the attribute "name" attached.

When I run it, it returns False. It should be showing True. I'm not sure what I've done wrong, and I'm fairly sure it's going to be a "Problem exists between keyboard and chair" incident, but I'm confused as to how this should work in practice.


Solution

  • The code you have provided checks for the attribute on the class Dog itself, and not an instance of the class Dog. In python, classes are objects of type type. So in your test code you are checking if an object of type type has the attribute name. From your description, you want to test if an object of class Dog has the attribute name. To do that, first you need to create an object of class Dog. Your test should look like:

    from utils.attribute_1 import Dog
    
    
    def test_Dog():
      my_pet = Dog('tuffy', 'pomeranian')  # creating an object of class Dog
      assert hasattr(my_pet, 'name')
    

    It also a good idea to test if the object you created has the expected value - the above test could have passed if objects of type type had the attribute name and you would have been none the wiser.

    from utils.attribute_1 import Dog
    
    
    def test_Dog():
      my_pet = Dog('tuffy', 'pomeranian')  # creating an object of class Dog
      assert hasattr(my_pet, 'name')
      assert my_pet.name == 'tuffy'