为什么 unittest 不识别 SQLAlchemy 数据类型?
Why doesn't unittest recognize SQLAlchemy data type?
我写了一个函数,return是一个 SQLAlchemy 数据类型以及该类型的参数。但是,当我尝试测试该函数时,unittest 告诉我函数 returns 的类型与我期望的类型不匹配。但是,它似乎向我表明该函数的 return 和我的预期结果确实匹配。
简化的代码示例...
from sqlalchemy import Numeric
class TestStandardizeColDataTypes(unittest.TestCase):
def test_successful_numeric(self):
self.assertEqual(standardize_col_data_type('Dec'), Numeric(precision=12, scale=2))
这是单元测试结果显示的内容(来自 Pycharm)...
Numeric(precision=12, scale=2) != Numeric(precision=12, scale=2)
Expected :Numeric(precision=12, scale=2)
Actual :Numeric(precision=12, scale=2)
看起来它们确实相等。我试过将测试类型更改为 AssertIs 和 AssertIsInstance,但没有成功。
关于我在这里遗漏的任何想法?谢谢!
问题是您正在尝试比较两个未实现 __eq__
方法的对象之间的相等性。您可以在文档中看到显示 here.
出现这种行为的原因如下:
User-defined classes have eq() and hash() methods by default; with them, all objects compare unequal (except with themselves) and x.hash() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).
你可以找到更详细的描述here
一个选项是制作自定义 class,它继承自 Numeric
类型并定义 __eq__
方法。
另一种选择是@rdas 在他的评论中提到的:
You're better off comparing the precision and scale manually.
@aws_apprentice说的对。然而,一个简单的解决方法是比较 vars
函数返回的两个对象的属性字典:
self.assertEqual(vars(standardize_col_data_type('Dec')), vars(Numeric(precision=12, scale=2)))
这避免了必须分别对每个属性的名称进行硬编码以进行比较。
我写了一个函数,return是一个 SQLAlchemy 数据类型以及该类型的参数。但是,当我尝试测试该函数时,unittest 告诉我函数 returns 的类型与我期望的类型不匹配。但是,它似乎向我表明该函数的 return 和我的预期结果确实匹配。
简化的代码示例...
from sqlalchemy import Numeric
class TestStandardizeColDataTypes(unittest.TestCase):
def test_successful_numeric(self):
self.assertEqual(standardize_col_data_type('Dec'), Numeric(precision=12, scale=2))
这是单元测试结果显示的内容(来自 Pycharm)...
Numeric(precision=12, scale=2) != Numeric(precision=12, scale=2)
Expected :Numeric(precision=12, scale=2)
Actual :Numeric(precision=12, scale=2)
看起来它们确实相等。我试过将测试类型更改为 AssertIs 和 AssertIsInstance,但没有成功。
关于我在这里遗漏的任何想法?谢谢!
问题是您正在尝试比较两个未实现 __eq__
方法的对象之间的相等性。您可以在文档中看到显示 here.
出现这种行为的原因如下:
User-defined classes have eq() and hash() methods by default; with them, all objects compare unequal (except with themselves) and x.hash() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).
你可以找到更详细的描述here
一个选项是制作自定义 class,它继承自 Numeric
类型并定义 __eq__
方法。
另一种选择是@rdas 在他的评论中提到的:
You're better off comparing the precision and scale manually.
@aws_apprentice说的对。然而,一个简单的解决方法是比较 vars
函数返回的两个对象的属性字典:
self.assertEqual(vars(standardize_col_data_type('Dec')), vars(Numeric(precision=12, scale=2)))
这避免了必须分别对每个属性的名称进行硬编码以进行比较。