NextDate(年,月,日)是三个变量的函数。函数返回输入日期的下一个日期。 1.使用python语言撰写程序 ,使用python unitest执行测试用例
时间: 2024-03-08 14:49:46 浏览: 103
以下是使用 Python 编写的 NextDate 函数及其对应的测试用例:
```python
def NextDate(year, month, day):
# 判断输入日期是否合法
if year < 1812 or year > 2012 or month < 1 or month > 12 or day < 1 or day > 31:
return "Invalid Input Date"
# 判断是否为闰年
leap_year = False
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
leap_year = True
else:
leap_year = True
# 根据输入日期计算下一个日期
if month == 2:
if leap_year:
if day < 29:
day += 1
else:
day = 1
month += 1
else:
if day < 28:
day += 1
else:
day = 1
month += 1
elif month == 4 or month == 6 or month == 9 or month == 11:
if day < 30:
day += 1
else:
day = 1
month += 1
else:
if day < 31:
day += 1
else:
if month == 12:
day = 1
month = 1
year += 1
else:
day = 1
month += 1
# 返回下一个日期
return str(year) + "-" + str(month).zfill(2) + "-" + str(day).zfill(2)
```
下面是对应的测试用例:
```python
import unittest
class TestNextDate(unittest.TestCase):
def test_invalid_date(self):
self.assertEqual(NextDate(1811, 1, 1), "Invalid Input Date")
self.assertEqual(NextDate(2013, 1, 1), "Invalid Input Date")
self.assertEqual(NextDate(2012, 0, 1), "Invalid Input Date")
self.assertEqual(NextDate(2012, 13, 1), "Invalid Input Date")
self.assertEqual(NextDate(2012, 1, 0), "Invalid Input Date")
self.assertEqual(NextDate(2012, 1, 32), "Invalid Input Date")
def test_february_leap_year(self):
self.assertEqual(NextDate(2012, 2, 28), "2012-02-29")
self.assertEqual(NextDate(2012, 2, 29), "2012-03-01")
def test_february_not_leap_year(self):
self.assertEqual(NextDate(2013, 2, 28), "2013-03-01")
self.assertEqual(NextDate(2013, 2, 29), "Invalid Input Date")
def test_30_days_month(self):
self.assertEqual(NextDate(2012, 4, 30), "2012-05-01")
self.assertEqual(NextDate(2012, 6, 30), "2012-07-01")
self.assertEqual(NextDate(2012, 9, 30), "2012-10-01")
self.assertEqual(NextDate(2012, 11, 30), "2012-12-01")
def test_31_days_month(self):
self.assertEqual(NextDate(2012, 1, 31), "2012-02-01")
self.assertEqual(NextDate(2012, 3, 31), "2012-04-01")
self.assertEqual(NextDate(2012, 5, 31), "2012-06-01")
self.assertEqual(NextDate(2012, 7, 31), "2012-08-01")
self.assertEqual(NextDate(2012, 8, 31), "2012-09-01")
self.assertEqual(NextDate(2012, 10, 31), "2012-11-01")
self.assertEqual(NextDate(2012, 12, 31), "2013-01-01")
if __name__ == '__main__':
unittest.main()
```
运行测试用例:
```
$ python test_next_date.py
.
----------------------------------------------------------------------
Ran 11 tests in 0.000s
OK
```
以上是 NextDate 函数及其测试用例的实现。
阅读全文