Lecture 5 - CS50’s Introduction to Programming with Python (harvard.edu)
Notes
assert(断言)
calculator
def main():
x = int(input("What's x? "))
print("x squared is", square(x))
def square(n):
return n + n
if __name__ == "__main__":
main()
test_square
from calculator import square
def test_assert():
assert square(2) == 4
assert square(3) == 9
assert square(-2) == 4
assert square(-3) == 9
assert square(0) == 0
pytest
import pytest
from calculator import square
def test_positive():
assert square(2) == 4
assert square(3) == 9
def test_negative():
assert square(-2) == 4
assert square(-3) == 9
def test_zero():
assert square(0) == 0
def test_str():
with pytest.raises(TypeError):
square("cat")
pytest.raises
异常处理- pytest.raises 和
with
语句一起使用,成功断言到期望异常则测试通过,未断言到期望异常则测试失败 - 记得
import pytest
~
- pytest.raises 和
pytest test_xxxx.py
作业
test_twttr
twttr
def main():
get=input("Input:")
print("Output:",end="")#end=""保证不换行
shorten(get)
def shorten(word):
res=[]
for short in word:
if short.lower() in ['a','e','i','o','u']:
continue
else:
res.append(short)
# 注意要有返回值哈
# join拼接字符串
return "".join(res)
if __name__ == "__main__":
main()
test_twttr
from twttr import shorten
def test_shorten():
# 注意函数最好有返回值
assert shorten("aeiou") == ""
assert shorten("AEIOU") == ""
assert shorten("twitter") == "twttr"
assert shorten("tWitTer") == "tWtTr"
assert shorten("What's your name?") == "Wht's yr nm?"
assert shorten("1a2be") == "12b"
注意:
- 注意assert断言时,测试的函数最好有返回值来判断
- 在被测函数中,不要漏掉
if __name__ == "__main__":
main()
test_bank
bank
def main():
greet=input("Greeting:").strip().lower()
print(f"${value(greet)}")
def value(greeting):
if greeting.startswith("hello"):
res=0
elif greeting.startswith("h"):
res=20
else :
res=100
return res
if __name__ == "__main__":
main()
test_bank
from bank import value
def test_value():
# 注意函数最好有返回值
assert value("Hello") == 0
assert value("Hello, Newman") == 0
assert value("How you doing?") == 20
assert value("What's happening?") == 100
test_plates
plates
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s[0:2].isalpha() and 2<=len(s)<=6:
for ch in s[2:]:
#排除不是字母或者数字的
if ch.isalpha()==False and ch.isdigit()==False:
return False
for ch in s[2:]:
#字母的ok
if ch.isdigit():
if ch=="0":
return False
else:
#循环到第一位数字,无论怎样,都return,不再继续遍历ch
first_number_position=s.index(ch)
#s[i:j]切片
for i in s[first_number_position:]:
if i.isalpha():
return False
return True
#全是字母的情况
else:
return True
#排除前两位不是字母的和长度不对的
else:
return False
if __name__ == "__main__":
main()
test_plates
from plates import is_valid
def test_plates():
# 这里的返回值是true/false
assert is_valid("CS50") == 1
assert is_valid("CS05") == 0
assert is_valid("CS50P") == 0
assert is_valid("PI3.14") == 0
assert is_valid("123456") == 0
assert is_valid("H") == 0
assert is_valid("OUTATIME") == 0
test_fuel
fuel
def main():
print(gauge(convert(input("Input:"))))
def convert(fraction):
while True:
try:
x,y=fraction.split("/")
x=int(x)
y=int(y)
if y==0:
# 将被除数为0的异常主动触发
raise ValueError
# 只有正常的数才能返回
if 0<= x/y <=1:
res=round(100*x/y)
return res
except ValueError:
pass
def gauge(res):
if res<=1:
return "E"
elif res>=99:
return "F"
else:
return f"{res:}%"
if __name__ == "__main__":
main()
test_fuel
from fuel import gauge
from fuel import convert
import pytest
def test_fuel():
# gauge返回的不应该是print,而应该是值!
assert gauge(convert('3/4')) == "75%"
assert gauge(convert('1/4')) == "25%"
assert gauge(convert('4/4')) == "F"
assert gauge(convert('0/4')) == "E"
with pytest.raises(ValueError):
convert("x/y")
with pytest.raises(ValueError):
convert("three/four")
with pytest.raises(ValueError):
convert("10/3")
with pytest.raises(ValueError):
convert("1.5/4")
with pytest.raises(ValueError):
convert("5-4")
with pytest.raises(ZeroDivisionError):
convert("1/0")
def test_gauge():
assert gauge(0) == "E"
assert gauge(1) == "E"
assert gauge(100) == "F"
assert gauge(99) == "F"
assert gauge(2) == "2%"
assert gauge(40) == "40%"
assert gauge(98) == "98%"
难点:
with pytest.raises(ValueError):
成功断言到期望异常则测试通过- 注意返回值