如何断言类型等于给定值

ana*_*rce 7 python pytest python-3.x

我正在编写一个方法的测试,我想验证该方法返回一个特定的类型.但是,当我尝试这个时,我收到一个错误.

def search_emails(mail):  
  data = mail.uid('search')
  raw_email = data[0][1]  
  return raw_email
Run Code Online (Sandbox Code Playgroud)

类型(raw_email)是: <class 'bytes'>

当我运行此测试时:

def test_search_emails_returns_bytes():  
  result = email_handler.search_emails(mail)
  assert type(result) == "<class 'bytes'>"
Run Code Online (Sandbox Code Playgroud)

我收到这个错误.我如何陈述断言以便测试通过?或者有更好的方法来编写测试吗?

E       assert <class 'bytes'> == "<class 'bytes'>"
Run Code Online (Sandbox Code Playgroud)

小智 10

您需要使用 isinstance,它是一个用于类型检查的内置函数

def test_search_emails_returns_bytes():  
  result = email_handler.search_emails(mail)
  assert isinstance(result, bytes)
Run Code Online (Sandbox Code Playgroud)

  • 在某些情况下,优先选择“isinstance(X, Y)”而不是“type(X) is Y”可能很重要,因为“isinstance”也会为子类返回“True”。 (2认同)

Zac*_*tes 9

您可以使用is运算符检查变量是否为特定类型

my_var = 'hello world'
assert type(my_var) is str
Run Code Online (Sandbox Code Playgroud)


joa*_*yra 5

如果您想检查某个类是否特定于某个类,则 isinstance 不会这样做,因为即使它是派生类,它也会返回 True,而不是您要检查的类。您可以将类型作为这样的字符串获取:

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
Run Code Online (Sandbox Code Playgroud)

这实际上会返回“lst”、“int”等。

在您的代码中,这将转换为如下内容:

assert type(result).__name__ == "bytes"
Run Code Online (Sandbox Code Playgroud)


Ran*_*esh 5

既然您提到您正在使用method,那么,assertIsInstance可能会很方便:

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()
Run Code Online (Sandbox Code Playgroud)

有关断言方法的列表,请向下滚动此处