Python编写测试脚本
时间: 2023-11-05 17:04:02 浏览: 31
以下是一个简单的Python测试脚本示例:
```python
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('hello'.upper(), 'HELLO')
def test_isupper(self):
self.assertTrue('HELLO'.isupper())
self.assertFalse('Hello'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
```
这个脚本使用Python的unittest模块来编写测试用例。在上面的示例中,我们定义了一个名为TestStringMethods的测试类,其中包含三个测试方法:test_upper,test_isupper和test_split。
每个测试方法都使用assert语句来检查代码的行为是否符合预期。例如,test_upper方法使用assertEqual来检查字符串“hello”是否被正确转换为“HELLO”。
最后,我们使用if __name__ == '__main__'语句来运行测试脚本。这将告诉Python在模块被直接执行时运行测试。