【问题标题】:Unit Testing in python and AssertionError: False != Truepython 中的单元测试和 AssertionError: False != True
【发布时间】:2016-11-24 11:08:06
【问题描述】:

我通常在 python 中进行一些单元测试。我得到下面提到的 AssertionError。我想检查温度范围,如果它小于 30 并且大于 25 ,那么代码应该通过,但它给了我错误。我不知道我在哪里犯错了。

test_csv_read_data_headers (__main__.ParseCSVTest) ... ok
test_data_fuelConsumption (__main__.ParseCSVTest) ... ok
test_data_temperature (__main__.ParseCSVTest) ...FAIL
test_data_timestamp (__main__.ParseCSVTest) ... ok

================================================ ========================

失败:test_data_temp (ma​​in.ParseCSVTest)

Traceback (most recent call last):
File "try.py", line 36, in test_data_temperature
30 > ali > 25, True
AssertionError: False != True

Ran 4 tests in 0.014s

FAILED (failures=1)

我的测试失败的温度部分的代码如下。

def test_data_temperature(self):                
    column = [row[0].split()[3] for row in read_data(self.data)[1:]]                      
    ali = column[0:4]
    print ali                          
    self.assertEqual(
            30 > ali > 25, True 
            )

我在ali中打印数据,是列表的形式

['25.8', '25.6', '25.8', '25.8']  

我很困惑如何检查它的范围并做出断言以使其通过测试。如果有人给出提示或示例。我会很感激的。

【问题讨论】:

  • 如果它是一个列表,那么它在 30 到 25 之间确实是不正确的。

标签: python unit-testing assertion


【解决方案1】:

您正在将列表与整数进行比较。

您需要单独比较每个值(例如使用python 内置all)。尝试类似

self.assertTrue(all(30 > a > 25 for a in ali))

您还可以检查列表的minmax 值。稍微(可以忽略不计)性能更差(我认为?)但如果/当测试失败时会给你更多信息。

self.assertTrue(max(ali) < 30)
self.assertTrue(min(ali) > 25)

【讨论】:

  • 这仍然会失败,因为列表包含字符串,而不是数字。但这意味着测试正在发现问题,这很好!
  • @zeeshankhan:在比较中使用float(a)而不是a,将字符串转换为浮点数。
  • @zeeshankhan,RemcoGerlich 提出了一个很好的观点。测试失败,因为列表包含字符串而不是数字。您确定要更改为 test 以使其通过,而不是更改代码以将值存储为数值开始吗?
  • 这不是字符串,而是列表。列表中的项目是字符串。
  • 好吧,考虑一下 -165
猜你喜欢
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 2015-10-10
  • 2022-11-10
  • 2012-07-17
  • 2017-05-26
  • 1970-01-01
  • 2011-12-05
相关资源
最近更新 更多