How to assert that a type equals a given value

If you want to check that something is specifically of a class, isinstance won't do, because that will return True even if it is a derived class, not exactly the class you want to check against. You can get the type as a string like this:

def decide_type(raw_prop):
    """Returns the name of a type of an object.
    Keep in mind, type(type("a")) is Type,
                  type(type("a").__name__) is Str
    """
    type_as_string = type(first_raw_prop).__name__
    return type_as_string

That will actually return 'lst', 'int', and such.

In your code, that'd translate to something like this:

assert type(result).__name__ == "bytes"

You need to use isinstance, its a built in function for type checking

def test_search_emails_returns_bytes():  
  result = email_handler.search_emails(mail)
  assert isinstance(result, bytes)

Since you mentioned that you are using a method, then, assertIsInstance might be handy:

import unittest

def myfunc(name):
    return type(name)

class TestSum(unittest.TestCase):
    def test_type(self):
        result = myfunc('Micheal')
        self.assertIsInstance(result, str)

unittest.main()

For a list of assert methods, scroll down here:


You can use the is operator to check that a variable is of a specific type

my_var = 'hello world'
assert type(my_var) is str