Testing a Function

unit test and test case

  1. import unittest
  2. from name_function import get_formatted_name
  3. class NamesTestCase(unittest.TestCase):
  4. """Tests for 'name_function.py'"""
  5. def test_first_last_name(self):
  6. """Do names like 'Janis Joplin' work?"""
  7. formatted_name = get_formatted_name('janis', 'joplin')
  8. self.assertEqual(formatted_name, 'Janis Joplin')
  9. def test_first_middle_last_name(self):
  10. """Do names like 'Wolfgang Amadeus Mozart' work?"""
  11. formatted_name = get_formatted_name(
  12. 'wolfgang', 'mozart', 'amadeus'
  13. )
  14. self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
  15. if __name__ == '__main__':
  16. unittest.main()
  • 使用单元测试编写测试用例可以用来自动测试,不用手动执行函数来测试
  • 测试用例中每个以test_开头的函数都会自动执行
  • 很多测试框架都会先导入测试文件再 运行。导入文件时,解释器将在导入的同时执行它。
  • if 代码块检查特殊变量 name ,这个变量是在程序执行时设置的。

    1. 如果这个文件作为主程序执行,变

    name 将被设置为’main‘ 。在这里,调用unittest.main() 来运
    行测试用例。
    如果这个文件被测试框架导入,变量name 的值将不 是’main‘ ,因此不会调用unittest.main() 。

Testing a Class

常用的assert methods
image.png
有一个class如下

  1. class AnonymousSurvey:
  2. """Collect anonymous answers to a survey question."""
  3. def __init__(self, question):
  4. """Store a question, and prepare to store responses."""
  5. self.question = question
  6. self.responses = []
  7. def show_question(self):
  8. """Show the survey question."""
  9. print(self.question)
  10. def store_response(self, new_response):
  11. """Store a single response to the survey."""
  12. self.responses.append(new_response)
  13. def show_results(self):
  14. """Show all the responses that have been given."""
  15. print("Survey results:")
  16. for response in self.responses:
  17. print(f"- {response}")

编写测试

  1. import unittest
  2. from survey import AnonymousSurvey
  3. class TestAnonymousSurvey(unittest.TestCase):
  4. """Tests for the class AnonymousSurvey"""
  5. def test_store_single_response(self):
  6. """Test that a single response is stored"""
  7. question = "What language did you first learn to speak?"
  8. my_survey = AnonymousSurvey(question)
  9. my_survey.store_response('English')
  10. self.assertIn('English', my_survey.responses)
  11. def test_store_three_responses(self):
  12. """Test that three individual responses are stored properly."""
  13. question = "What language did you first learn to speak?"
  14. my_survey = AnonymousSurvey(question)
  15. responses = ['English', 'Spanish', 'Mandarin']
  16. for response in responses:
  17. my_survey.store_response(response)
  18. for response in responses:
  19. self.assertIn(response, my_survey.responses)
  20. if __name__ == '__main__':
  21. unittest.main()

setUp()

  • unittest.TestCase有一个setUp()方法,在setUp()内创建的对象,其他test_方法都能使用(必须加self.)
  • Python在运行test_方法前会先运行setUp()方法(关键) ```python import unittest from survey import AnonymousSurvey

class TestAnonymousSurvey(unittest.TestCase): “””Tests for the class AnonymousSurvey”””

  1. def setUp(self):
  2. """
  3. Create a survey and a set of responses for use in all test methods.
  4. """
  5. question = "What language did you first learn to speak?"
  6. self.my_survey = AnonymousSurvey(question)
  7. self.responses = ['English', 'Spanish', 'Mandarin']
  8. def test_store_single_response(self):
  9. """Test that a single response is stored"""
  10. self.my_survey.store_response(self.responses[0])
  11. self.assertIn('English', self.my_survey.responses)
  12. def test_store_three_responses(self):
  13. """Test that three individual responses are stored properly."""
  14. for response in self.responses:
  15. self.my_survey.store_response(response)
  16. for response in self.responses:
  17. self.assertIn(response, self.my_survey.responses)

if name == ‘main‘: unittest.main() ``` When a test case is running, Python prints one character for each unit test as it is completed. A passing test prints a dot, a test that results in an error prints an E, and a test that results in a failed assertion prints an F.