在Python Unittest.Mock 中模擬開啟檔案
在測試使用檔案操作的Python 程式碼時,有效地模擬開啟檔案的行為至關重要。在with 語句中使用open 時會出現一種特定情況,如以下程式碼所示:
<code class="python">def testme(filepath): with open(filepath) as f: return f.read()</code>
Python 3
要模擬此open 操作,請使用unittest.mock 與mock_open 結合使用,它是mock 框架的一部分。 patch 充當上下文管理器,傳回用於替換修補物件的物件:
<code class="python">from unittest.mock import patch, mock_open with patch("builtins.open", mock_open(read_data="data")) as mock_file: assert open("path/to/open").read() == "data" mock_file.assert_called_with("path/to/open")</code>
或者,patch 也可以用作裝飾器。然而,使用mock_open()的結果作為新參數可能會很麻煩。相反,請利用patch 的new_callable 參數,並記住patch 未使用的其他參數將傳遞給new_callable 函數:
<code class="python">@patch("builtins.open", new_callable=mock_open, read_data="data") def test_patch(mock_file): assert open("path/to/open").read() == "data" mock_file.assert_called_with("path/to/open")</code>
請注意,在此實例中,patch 將提供模擬物件作為測試函數的參數.
Python 2
對於Python 2,需要修補__builtin__.open 並單獨導入模擬:
<code class="python">from mock import patch, mock_open with patch("__builtin__.open", mock_open(read_data="data")) as mock_file: assert open("path/to/open").read() == "data" mock_file.assert_called_with("path/to/open")</code>
以上是如何在 Python Unittest.Mock 中模擬開啟的檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver Mac版
視覺化網頁開發工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版
中文版,非常好用

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!