【问题标题】:How to write a pytest or unittest on my code?如何在我的代码上编写 pytest 或 unittest?
【发布时间】:2021-07-04 22:07:20
【问题描述】:

我是单元测试的新手。我正在尝试测试是否调用了函数以及下面的调度时间是否正确。

python 文件名是#schedule.py

def screenshot():
   ob=Screenshot_Clipping.Screenshot()
   driver.get(url)
   img_url=ob.full_Screenshot(driver, save_path = path)
   email_it(path)
   driver.close()
screenshot()

【问题讨论】:

  • 把文件名改成 test_schedule.py ,pytest 会扫描带有 test_* 的文件,你需要添加断言语句来标记测试用例是通过还是失败
  • 我在这里看到的几个问题。我建议阅读documentation。最初的指南应该给你一个很好的介绍。指出代码中的几个问题以提供帮助:在您的 test_capture 中,您正尝试调用 assert_called_once。但是,您永远不会“嘲笑”schedule.function1.capture 中的任何内容。因此,尝试从您的 real 代码中访问 mock 方法 assert_called_once 是行不通的。
  • 另外,assert_called_once 是一种方法,所以当你开始工作时,一定要调用它:assert_called_once()。在您的第二个测试文件test_schedule2.py 中指出的另一项。您的 assert 没有正确使用 equality。您想使用== 而不是=。单 = 用于赋值,双 == 用于相等。
  • @idjaw 你能帮我举个例子来说明我如何在我的代码中使用 mock 吗?

标签: python unit-testing pytest python-unittest python-mock


【解决方案1】:

试试这个,

def test_screenshot(mocker):
    url = 'url'
    path = /your/path/

    mocker.patch('screenshot.env', return_value = (url, path))
    
    mocker.patch('screenshot.email_it', return_value = (path))

    screenshot()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2017-11-26
    • 1970-01-01
    • 2018-03-24
    相关资源
    最近更新 更多