單元測試 python_Python單元測試簡介

單元測試 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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391198.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391198.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391198.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

飛行模式的開啟和關閉

2019獨角獸企業重金招聘Python工程師標準>>> if(Settings.System.getString(getActivity().getContentResolver(),Settings.Global.AIRPLANE_MODE_ON).equals("0")) { Settings.System.putInt(getActivity().getContentResolver(),Settings.Global.AIRPLA…

消解原理推理_什么是推理統計中的Z檢驗及其工作原理?

消解原理推理I Feel:我覺得: The more you analyze the data the more enlightened, data engineer you will become.您對數據的分析越多,您將變得越發開明。 In data engineering, you will always find an instance where you need to establish whet…

pytest+allure測試框架搭建

https://blog.csdn.net/wust_lh/article/details/86685912 https://www.jianshu.com/p/9673b2aeb0d3 定制化展示數據 https://blog.csdn.net/qw943571775/article/details/99634577 環境說明: jdk 1.8 python 3.5.3 allure-commandline 2.13.0 文檔及下載地址&…

lintcode433 島嶼的個數

島嶼的個數 給一個01矩陣,求不同的島嶼的個數。 0代表海,1代表島,如果兩個1相鄰,那么這兩個1屬于同一個島。我們只考慮上下左右為相鄰。 您在真實的面試中是否遇到過這個題? Yes樣例 在矩陣: [[1, 1, 0, …

大數據分析要學習什么_為什么要學習數據分析

大數據分析要學習什么The opportunity to leverage insights from data has never been greater.利用來自數據的洞察力的機會從未如此大。 Humans tend to generate a lot of data each day - from heart rates to favorite songs, fitness goals and movie preferences. You …

POJ - 3257 Cow Roller Coaster (背包)

題目大意:要用N種材料建一條長為L的路,如今給出每種材料的長度w。起始地點x。發費c和耐久度f 問:在預算為B的情況下,建好這條路的最大耐久度是多少 解題思路:背包問題 dp[i][j]表示起始地點為i。發費為j的最大耐久度…

leetcode 1473. 粉刷房子 III(dp)

在一個小城市里,有 m 個房子排成一排,你需要給每個房子涂上 n 種顏色之一(顏色編號為 1 到 n )。有的房子去年夏天已經涂過顏色了,所以這些房子不需要被重新涂色。 我們將連續相同顏色盡可能多的房子稱為一個街區。&a…

大學生信息安全_給大學生的信息

大學生信息安全You’re an undergraduate. Either you’re graduating soon (like me) or you’re in the process of getting your first college degree. The process is not easy and I can only assume how difficult the pressures on Masters and Ph.D. students are. Ho…

打破冷漠僵局文章_保持冷靜并打破僵局-最佳

打破冷漠僵局文章Hack The Box (HTB) is an online platform allowing you to test your penetration testing skills. It contains several challenges that are constantly updated. Some of them simulating real world scenarios and some of them leaning more towards a …

使用DOM Breakpoints找到修改屬性的Javascript代碼

使用Chrome開發者工具的DOM斷點功能可以讓您快速找到修改了某一個DOM元素的Javascript代碼。 在Chrome開發者工具里,選中想要監控的DOM元素,點擊右鍵,選擇Break on->Attributes modifications: 之后在DOM Breakpoints的tab里能看到對應的斷…

特斯拉最安全的車_特斯拉現在是最受歡迎的租車選擇

特斯拉最安全的車Have you been curious to know which cars are most popular in US and what are their typical rental fares in various cities? As the head of Product and Data Science at an emerging technology start-up, Ving Rides, these were some of the quest…

leetcode 740. 刪除并獲得點數(dp)

給你一個整數數組 nums ,你可以對它進行一些操作。 每次操作中,選擇任意一個 nums[i] ,刪除它并獲得 nums[i] 的點數。之后,你必須刪除每個等于 nums[i] - 1 或 nums[i] 1 的元素。 開始你擁有 0 個點數。返回你能通過這些操作…

WebSocket入門

WebSocket前言  WebSocket是HTML5的重要特性,它實現了基于瀏覽器的遠程socket,它使瀏覽器和服務器可以進行全雙工通信,許多瀏覽器(Firefox、Google Chrome和Safari)都已對此做了支持。 在WebSocket出現之前&#xff…

安卓游戲開發推箱子_保持冷靜并砍箱子-開發

安卓游戲開發推箱子Hack The Box (HTB) is an online platform allowing you to test your penetration testing skills. It contains several challenges that are constantly updated. Some of them simulating real world scenarios and some of them leaning more towards …

自定義TabLayout

本文為kotlin仿開眼視頻Android客戶端的后續補充內容,本篇為大家介紹如何對TabLayout進行定制使用,基于項目需求,本篇主要對部分功能進行了定制,如:指示器距離文字的距離、文字選中加粗、文字選中變大等 本文部分代碼參…

ml dl el學習_DeepChem —在生命科學和化學信息學中使用ML和DL的框架

ml dl el學習Application of Machine Learning and Deep Learning for Drug Discovery, Genomics, Microsocopy and Quantum Chemistry can create radical impact and holds the potential to significantly accelerate the process of medical research and vaccine developm…

響應式網站設計_通過這個免費的四小時課程,掌握響應式網站設計

響應式網站設計This video tutorial from Kevin Powell teaches you to build responsive websites from scratch. 凱文鮑威爾(Kevin Powell)的這段視頻教程教您從頭開始構建響應式網站。 The course starts with explaining the core concepts needed to start thinking resp…

2017-2018-1 20179215《Linux內核原理與分析》第二周作業

20179215《Linux內核原理與分析》第二周作業 這一周主要了解了計算機是如何工作的,包括現在存儲程序計算機的工作模型、X86匯編指令包括幾種內存地址的尋址方式和push、pop、call、re等幾個重要的匯編指令。主要分為兩部分進行這周的學習總結。第一部分對學習內容進…

python:單例模式--使用__new__(cls)實現

單例模式:即一個類有且僅有一個實例。 那么通過python怎么實現一個類只能有一個實例呢。 class Earth:"""假如你是神,你可以創造地球"""print 歡迎來到地球# 生成一個地球 a Earth() print id(a)# 再生成一個地球 b Ear…

重學TCP協議(5) 自連接

1.自連接是什么 在發起連接時,TCP/IP的協議棧會先選擇source IP和source port,在沒有顯示調用bind()的情況下,source IP由路由表確定,source port由TCP/IP協議棧從local port range中選取尚未使用的port。 如果destination IP正…