日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python断言区间_断言整数在范围内

發布時間:2024/9/15 python 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python断言区间_断言整数在范围内 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我認為在內部使用assertTrue進行比較不是一個好主意-

這樣,您將丟失失敗消息中的任何信息:AssertionError: False is not true

這一點都沒有幫助,你基本上回到了“原始的”assert并且你失去了很多unittest方法的好處。

我建議:

創建自己的自定義斷言

您可以在其中打印更有意義的消息。例如:import unittest

class BetweenAssertMixin(object):

def assertBetween(self, x, lo, hi):

if not (lo <= x <= hi):

raise AssertionError('%r not between %r and %r' % (x, lo, hi))

class Test1(unittest.TestCase, BetweenAssertMixin):

def test_between(self):

self.assertBetween(999, 998, 1000)

def test_too_low(self):

self.assertBetween(997, 998, 1000)

def test_too_high(self):

self.assertBetween(1001, 998, 1000)

if __name__ == '__main__':

unittest.main()

然后您將得到以下輸出(縮寫):======================================================================

FAIL: test_too_high (__main__.Test1)

----------------------------------------------------------------------

Traceback (most recent call last):

File "example.py", line 19, in test_too_high

self.assertBetween(1001, 998, 1000)

File "example.py", line 8, in assertBetween

raise AssertionError('%r is not between %r and %r' % (x, lo, hi))

AssertionError: 1001 is not between 998 and 1000

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

FAIL: test_too_low (__main__.Test1)

----------------------------------------------------------------------

Traceback (most recent call last):

File "example.py", line 16, in test_too_low

self.assertBetween(997, 998, 1000)

File "example.py", line 8, in assertBetween

raise AssertionError('%r is not between %r and %r' % (x, lo, hi))

AssertionError: 997 is not between 998 and 1000

----------------------------------------------------------------------

或者使用assertLessEqual和assertGreaterEqual

如果不需要自定義斷言(它確實添加了另一條回溯記錄和幾行代碼):...

def test_no_custom_assert(self):

my_integer = 100

self.assertGreaterEqual(my_integer, 998)

self.assertLessEqual(my_integer, 1000)

...

比assertTrue(998 <= my_integer <= 1000)長一點(如果只使用一次的話,總長度可能比添加自定義斷言短),但是仍然會收到很好的失敗消息(也沒有附加的回溯記錄):======================================================================

FAIL: test_no_custom_assert (__main__.Test1)

----------------------------------------------------------------------

Traceback (most recent call last):

File "example.py", line 23, in test_no_custom_assert

self.assertGreaterEqual(my_integer, 998)

AssertionError: 100 not greater than or equal to 998

總結

以上是生活随笔為你收集整理的python断言区间_断言整数在范围内的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。