Auto commit

上级 3f5ed1d0
import random
import unittest
from unittest.mock import patch
import random
import io
import sys
import unittest
import random
from unittest import mock
def guess_number():
number = random.randint(1, 100)
count = 0
while True:
count += 1
guess = input("请输入一个 1-100 之间的整数:")
if not guess.isdigit() or int(guess) < 1 or int(guess) > 100:
print("输入不合法,请重新输入!")
elif int(guess) < number:
print("猜的数字太小了,再试试!")
elif int(guess) > number:
print("猜的数字太大了,再试试!")
else:
print("恭喜你,猜对了!你总共猜了 %d 次。" % count)
break
return count
from main import guess_number
class TestGuessNumber(unittest.TestCase):
@patch('sys.stdout', new_callable=io.StringIO)
@patch('random.randint')
@patch('builtins.input')
def test_input(self, mock_input, mock_randint, mock_stdout):
mock_randint.return_value = 50 # 将随机数固定为50
mock_input.side_effect = ['0', '101', 'abc', '50']
count = guess_number()
print(mock_stdout.getvalue())
self.assertEqual(mock_stdout.getvalue(), '输入不合法,请重新输入!\n输入不合法,请重新输入!\n输入不合法,请重新输入!\n恭喜你,猜对了!你总共猜了 4 次。\n')
#self.assertEqual(count, 1)
if __name__ == '__main__':
unittest.main()
if __name__ == '__main__':
unittest.main()
# 生成一个随机数
number = random.randint(1, 100)
# 记录猜的次数
count = 0
# 循环猜数字
while True:
guess = int(input("请猜一个1到100之间的数字:"))
count += 1
if guess == number:
print("恭喜你猜对了!你一共猜了%d次。" % count)
break
elif guess < number:
print("猜的数字太小了,请再猜一次。")
else:
print("猜的数字太大了,请再猜一次。")
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册