Search code examples
pythonpython-3.xpytest

How to assert that a type equals a given value


I am writing a test for a method and I want to validate that the method returns a specific type. However, when I try this I get an error.

def search_emails(mail):  
  data = mail.uid('search')
  raw_email = data[0][1]  
  return raw_email

The type(raw_email) is: <class 'bytes'>

When I run this test:

def test_search_emails_returns_bytes():  
  result = email_handler.search_emails(mail)
  assert type(result) == "<class 'bytes'>"

I get this error. How can I state the assertion so the test will pass? Or is there a better way to write the test?

E       assert <class 'bytes'> == "<class 'bytes'>"

Solution

  • You can use the isinstance function to check that a value is of a specific type:

    my_var = 'hello world'
    assert isinstance(my_var, str)