單元測試 python
You just finished writing a piece of code and you are wondering what to do. Will you submit a pull request and have your teammates review the code? Or will you manually test the code?
您剛剛編寫了一段代碼,并且想知道該怎么做。 您會提交拉取請求并讓您的隊友查看代碼嗎? 還是您將手動測試代碼?
You should do both of these things, but with an additional step: you need to unit test your code to make sure that the code works as intended.
您應該同時完成這兩項工作,但又需要執行額外的步驟:您需要對代碼進行單元測試,以確保代碼能夠按預期工作。
Unit tests can pass or fail, and that makes them a great technique to check your code. In this tutorial, I will demonstrate how to write unit tests in Python and you'll see how easy it is to get them going in your own project.
單元測試可以通過或失敗,這使它們成為檢查代碼的好技術。 在本教程中,我將演示如何用Python編寫單元測試,并且您會發現將它們放入自己的項目中是多么容易。
入門 (Getting started)
The best way you can understand testing is if you do it hands-on. For that purpose, in a file named name_function.py, I will write a simple function that takes a first and last name, and returns a full name:
理解測試的最好方法是親自進行測試。 為此,在名為name_function.py的文件中,我將編寫一個簡單的函數,該函數具有名字和姓氏,并返回全名:
#Generate a formatted full name
def formatted_name(first_name, last_name):full_name = first_name + ' ' + last_namereturn full_name.title()
The function formatted_name() takes the first and the last name and combines them with a space between to form a full name. It then capitalizes the first letter of every word. To check that this code works, you need to write some code that uses this function. In names.py I will write some simple code that lets users enter their first and last names:
函數formatted_name()接受名字和姓氏,并將其與空格之間組合起來以形成全名。 然后,將每個單詞的首字母大寫。 要檢查此代碼是否有效,您需要編寫一些使用此功能的代碼。 在names.py中,我將編寫一些簡單的代碼,讓用戶輸入名字和姓氏:
from name_function import formatted_nameprint("Please enter the first and last names or enter x to E[x]it.")while True:first_name = input("Please enter the first name: ")if first_name == "x":print("Good bye.")breaklast_name = input("Please enter the last name: ")if last_name == "x":print("Good bye.")breakresult = formatted_name(first_name, last_name)print("Formatted name is: " + result + ".")
This ?code imports formatted_name() from name_function.py and on running, allows the user to enter a series of first and last names and shows the formatted full names.
該代碼從name_function.py中導入formatted_name()并在運行時導入,允許用戶輸入一系列的名字和姓氏,并顯示格式化的全名。
單元測試和測試用例 (Unit test and Test cases)
There is a module in Python’s standard library called unittest which contains tools for testing your code. Unit testing checks if all specific parts of your function’s behavior are correct, which will make integrating ?them together with other parts much easier.
Python標準庫中有一個名為unittest的模塊,其中包含用于測試代碼的工具。 單元測試檢查功能行為的所有特定部分是否正確,這將使它們與其他部分的集成更加容易。
Test case is a collection of unit tests which together proves that a ?function works as intended, inside a full range of situations in which that function may find itself and that it’s expected to handle. Test case should consider all possible kinds of input a function could receive from users, and therefore should include tests to represent each of these situations.
測試用例是單元測試的集合,這些測試一起證明該功能可以按預期工作,并且可以在該功能可能會發現自己并有望處理的所有情況下發揮作用。 測試用例應考慮功能可以從用戶那里收到的所有可能的輸入,因此,測試用例應包括代表每種情況的測試。
通過考試 (Passing a test)
Here’s a typical scenario for writing tests:
這是編寫測試的典型方案:
First you need to create a test file. Then import the unittest module, define the testing class that inherits from unittest.TestCase, and lastly, write a series of methods to test all the cases of your function’s behavior.
首先,您需要創建一個測試文件。 然后導入unittest模塊,定義從unittest.TestCase繼承的測試類,最后??編寫一系列方法來測試函數行為的所有情況。
There’s a line by line explanation below the following code:
在以下代碼下有逐行說明:
import unittest
from name_function import formatted_nameclass NamesTestCase(unittest.TestCase):def test_first_last_name(self):result = formatted_name("pete", "seeger")self.assertEqual(result, "Pete Seeger")
First, you need to import a unittest and the function you want to test, formatted_name() . Then you create a class, for example NamesTestCase, that will contain tests for your formatted_name() function. This class inherits from the class unittest.TestCase.
首先,您需要導入一個單元測試和要測試的函數formatted_name()。 然后,創建一個類,例如NamesTestCase,它將包含對您的formatted_name()函數的測試。 該類繼承自unittest.TestCase類。
NamesTestCase contains a single method that tests one part of formatted_name() . You ?can call this method test_first_last_name().
NamesTestCase包含用于測試formatted_name()的一部分的單個方法。 您可以調用此方法test_first_last_name()。
Remember that every method that starts with “test_” will be run automatically when you run test_name_function.py.
請記住,當您運行test_name_function.py時,所有以“ test_”開頭的方法都將自動運行。
Within test_first_last_name() test method, you call the function you want to test and store a return value. In this example we are going to call ?formatted_name() with the arguments “pete” and “seeger” , and store the ?result in the resulting variable.
在test_first_last_name()測試方法中,調用要測試的函數并存儲返回值。 在此示例中,我們將使用參數“ pete”和“ seeger”調用formatted_name(),并將結果存儲在結果變量中。
In the last line we will use the assert method. The assert method verifies that a result you received matches the result you expected to receive. And in this case we know that formatted_name() function will return full ?name with capitalized first letters, so we expect the result “Pete ?Seeger”. To check this, the unittest’s assertEqual() method is being ?used.
在最后一行,我們將使用assert方法。 assert方法驗證您收到的結果是否與預期收到的結果匹配。 在這種情況下,我們知道formatted_name()函數將返回全名,首字母大寫,因此我們期望結果為“ Pete Seeger”。 為了檢查這一點,使用了unittest的assertEqual()方法。
self.assertEqual(result, “Pete Seeger”)
This ?line basically means: Compare the value in the resulting variable with “Pete Seeger” and if they are equal it’s OK, but if they are not let me know.
該行的基本含義是:將結果變量中的值與“ Pete Seeger”進行比較,如果它們相等,則可以,但是如果不告訴我。
On running test_name_function.py you are expected to get a OK meaning that the test has passed.
在運行test_name_function.py時,您將獲得一個OK,表示測試已通過。
Ran 1 test in 0.001sOK
測試失敗 (Failing a test)
To show you what a failing test looks like I’m going to modify a ?formatted_name() function by including a new middle name argument.
為了向您展示測試失敗的樣子,我將通過添加一個新的中間名參數來修改formatted_name()函數。
So I’m going to rewrite the function to look like this:
因此,我將重寫該函數,使其看起來像這樣:
#Generate a formatted full name including a middle name
def formatted_name(first_name, last_name, middle_name):full_name = first_name + ' ' + middle_name + ' ' + last_namereturn full_name.title()
This version of formatted_name() will work for people with middle names, but when you test it you will see that the function is broken for people who don’t have a middle name.
這個版本的formatted_name()適用于具有中間名的人,但是在測試它時,您會發現該功能對于沒有中間名的人而言是無效的。
So when you run the test_name_function.py you will get the output that looks something like this:
因此,當您運行test_name_function.py時,您將獲得如下所示的輸出:
Error
Traceback (most recent call last):File “test_name_function.py”, line 7, in test_first_last_nameresult = formatted_name(“pete”, “seeger”)TypeError: formatted_name() missing 1 required positional argument: ‘middle_name’Ran 1 test in 0.002sFAILED (errors=1)
In the output you will see information that will tell you all you need to know where the test fails:
在輸出中,您將看到信息,告訴您所有需要知道測試失敗的地方:
- First item in the output is the Error telling you that at least one test in test case resulted in an error. 輸出中的第一項是錯誤,它告訴您測試用例中至少有一個測試導致錯誤。
- Next you’ll see the file and method in which the error occurred. 接下來,您將看到發生錯誤的文件和方法。
- After that you will see the line in which the error occurred. 之后,您將看到發生錯誤的行。
- And what kind of error it is, in this case we are missing 1 argument “middle_name”. 這是什么錯誤,在這種情況下,我們缺少1個參數“ middle_name”。
- You will also see the number of run tests, the time needed for the tests to ?complete, and a textual message that represents the status of the tests with number of errors that occurred. 您還將看到運行測試的數量,完成測試所需的時間以及一條文本消息,該文本消息表示測試的狀態以及發生的錯誤數量。
測試失敗時該怎么辦 (What to do when the test has failed)
A passing test means the function is behaving according to what’s expected from it. However, a failing test means there’s more fun ahead of you.
通過測試意味著該功能正在按照預期的方式運行。 但是,失敗的測試意味著您還有更多的樂趣。
I’ve seen couple of programmers that prefer to change the test instead of improving the code — but don’t to that. Spend a little more time to fix ?the issue, as it will help you to better understand the code and save ?time in the long run.
我見過一些程序員喜歡更改測試而不是改進代碼,但是他們并不想這么做。 花更多的時間來解決此問題,因為從長遠來看,它將幫助您更好地理解代碼并節省時間。
In this example, our function formatted_name() first required two ?parameters, and now as it is rewritten it requires one extra: a middle name. Adding a middle name to our function broke the desired behavior of ?it. Since the idea is not to make changes to the tests, the best solution is to make middle name optional.
在此示例中,我們的函數formatted_name()首先需要兩個參數,而現在在重寫它時,它又需要一個額外的參數:中間名。 在我們的函數中添加中間名會破壞它的預期行為。 由于不打算更改測試,因此最好的解決方案是使中間名可選。
After we do this the idea is to make the tests pass when the first and last name are used, for example “Pete Seeger”, as well as when first, last and middle names are used, for example “Raymond Red Reddington”. So ?let’s modify the code of formatted_name() once again:
完成此操作后,我們的想法是使測試在使用名字和姓氏(例如“ Pete Seeger”)以及使用名字,姓氏和中間名(例如“ Raymond Red Reddington”)時通過。 因此,讓我們再次修改formatted_name()的代碼:
#Generate a formatted full name including a middle name
def formatted_name(first_name, last_name, middle_name=''):if len(middle_name) > 0:full_name = first_name + ' ' + middle_name + ' ' + last_nameelse:full_name = first_name + ' ' + last_namereturn full_name.title()
Now the function should work for names with and without the middle name.
現在,該函數應該適用于帶有或不帶有中間名的名稱。
And to make sure it still works with “Pete Seeger” run the test again:
為了確保它仍然可以與“ Pete Seeger”一起使用,請再次運行測試:
Ran 1 test in 0.001sOK
And this is what I intended to show you: It’s always better to make changes to your code to fit your tests than other way around. Now the time has come to add a new test for names that do have a middle name.
這就是我想要向您顯示的內容:更改代碼以適合您的測試總是比其他方法更好。 現在該是為確實具有中間名稱的名稱添加新測試的時候了。
添加新測試 (Adding new tests)
Write a new method to the NamesTestCase class that will test for middle names:
將新方法寫入NamesTestCase類,以測試中間名:
import unittest
from name_function import formatted_nameclass NamesTestCase(unittest.TestCase):def test_first_last_name(self):result = formatted_name("pete", "seeger")self.assertEqual(result, "Pete Seeger")def test_first_last_middle_name(self):result = formatted_name("raymond", "reddington", "red")self.assertEqual(result, "Raymond Red Reddington")
After you run the test, both tests should pass:
運行測試后,兩個測試都應通過:
Ran 2 tests in 0.001sOK
Bra gjort!
胸罩gjort!
You have written your tests to check if the function works using names with ?or without a middle name. Stay tuned for part 2 where I’ll talk more about testing in Python.
您已經編寫了測試以檢查該函數是否使用帶有或不帶有中間名的名稱。 請繼續關注第2部分,在該部分中,我將詳細討論Python測試。
Thank you for reading! Check out more articles like this on my freeCodeCamp profile: https://www.freecodecamp.org/news/author/goran/ and other fun stuff I build on my GitHub page: https://github.com/GoranAviani
感謝您的閱讀! 在我的freeCodeCamp個人資料上查看更多類似的文章: https ://www.freecodecamp.org/news/author/goran/和我在GitHub頁面上構建的其他有趣的東西: https : //github.com/GoranAviani
翻譯自: https://www.freecodecamp.org/news/an-introduction-to-testing-in-python/
單元測試 python