2017-06-04 14 views
6

我正在使用Python 3.6.1的Selenium 3.4.0。我在Python文檔中通過unittest模塊編寫了一個腳本,該模塊是基於Java的JUnit的內置Python,在Windows 8 Pro計算機,64位操作系統,x-64處理器上使用geckodriver 0.16.1和Mozilla Firefox 57.0。在我的測試方法test_search_in_python_org()我有以下線,效果很好:Selenium3.4.0-Python3.6.1:在使用unittest的Selenium-Python綁定中我如何決定何時使用self.assertIn或assert

def test_search_in_python_org(self): 
     driver = self.driver 
     driver.get("http://www.python.org") 
     self.assertIn("Python", driver.title) 
     elem = driver.find_element_by_name("q") 
     elem.send_keys("pycon") 
     elem.send_keys(Keys.RETURN) 
     assert "No results found." not in driver.page_source 

當我斷言「頁面標題」我使用的:self.assertIn("Python", driver.title)

但是,當我認定一個字符串(我的假設),在我使用的頁面源內:assert "No results found." not in driver.page_source

我的問題是決定我應該使用self.assertIn還是僅僅使用assert的因素/條件是什麼?

任何建議或指針都會有所幫助。

+0

檢查[this](https://stackoverflow.com/questions/2958169/what-are-the-advantages-or-difference-in-assert-false-and-self-assertfalse)問題 – Andersson

回答

5

看着Python unittestdocumentation並且還記得我曾經在這裏做過的一堆Django單元測試是我的發現。

使用案例:這是最簡單的事情,在我看來,兩者之間最大的區別

第一件事,就是在情況下,你可以使用每個命令。它們在測試類中都可以互換使用,但是,要使用assertIn命令,則需要導入unittest庫。 所以,說我想知道h是在hello。一個簡單的方式,通過assertIn命令來做到這一點是:

class MyTestCase(unittest.TestCase): 
    def is_h_in_hello(self): 
     self.assertIn("h", "hello") 

,然後我需要運行測試,也就是通過這個例子unittest.main(),爲了得到我的答案。 但使用assert命令,可以更容易地看到h是否在hello中。這很簡單,就像這樣:

assert "h" in "hello" 

但基本上,兩者都會給我同樣的答案。然而,兩種方法的區別在於第二種方法的簡單使用。

結果:

我的第二個不同是在Python Shell中的結果的可讀性。該庫的設計使命令非常具體。所以如果一個測試失敗了,你會收到一個非常明確的信息,說明哪裏出了問題。說現在你想看看b是在hello。通過類方法(簡單地改變"h""b")這樣做,運行測試後我們得到的消息是:

AssertionError: 'b' not found in 'hello' 

---------------------------------------------------------------------- 
Ran 1 test in 0.038s 

FAILED (failures=1) 

所以它很明確地告訴你:'b' not found in 'hello',這使得它非常方便地看到到底是什麼問題。但是,假設您通過assert命令執行相同的過程。產生的錯誤信息是這樣的:

Traceback (most recent call last): 
    File "<pyshell#2>", line 1, in <module> 
    assert "b" in "hello" 
AssertionError 

儘管它告訴你的錯誤類型(AssertionError),和回溯,它並沒有明確告訴你,"b" is NOT in "hello"。在這種簡單的情況下,很容易看到回溯,並說哦,沒有你好!但是,在更復雜的情況下,可能會很棘手,看看爲什麼會生成此錯誤消息。

總的來說,這兩種方法非常相似,並會得到你想要的結果,但本質上它歸結爲這裏和那裏的小差異,代碼行數少以及Shell消息的直接轉發方式。

+1

非常感謝細節。 – DebanjanB

0

在我看來,斷言是python中的內置關鍵字,它告訴程序的內部狀態。換句話說,通過assert關鍵字,你可以告訴你的代碼行爲。 就你而言,你不應該在測試用例中使用assert。

+0

我的意思是,當你在編寫測試時使用self.assert,否則使用assert – Erdenezul

相關問題