V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
patx
V2EX  ›  Python

Python 能否 mock 函数,只获取入参或返回值,不改变函数逻辑?

  •  
  •   patx · Feb 12, 2022 · 3567 views
    This topic created in 1536 days ago, the information mentioned may be changed or developed.

    对 Python 不是很熟悉,碰到这种情况,比如:

    函数 func1 有文件路径的入参,func1 是写入内容到该文件。

    我想写一个单元测试,只想获取入参或者返回值,做后续断言用,但是不覆盖 func1 的功能。

    我看了一下 Mock side_effect 之类的属性,是把函数功能覆盖掉了,有没有更好的方法?

    7 replies    2022-02-12 22:23:37 +08:00
    lanyi96
        1
    lanyi96  
       Feb 12, 2022
    装饰器?
    patx
        2
    patx  
    OP
       Feb 12, 2022
    @lanyi96 不改动该函数的前提下做单元测试,可以 mock 装饰器?
    imn1
        3
    imn1  
       Feb 12, 2022
    装饰器可以获取并继续跑原函数,在装饰器内输出到其他地方(全局变量或外存储)就行了

    如果可以修改原来代码,加个装饰器就可以了
    不能的话就继承过来再加

    可以看看 contextlib 和 inspect ,或许有用
    saber000
        4
    saber000  
       Feb 12, 2022   ❤️ 1
    side_effect 可以再指向原函数呀
    Trim21
        5
    Trim21  
       Feb 12, 2022   ❤️ 1
    mock.Mock(wraps=original_object)
    patx
        6
    patx  
    OP
       Feb 12, 2022
    @Trim21 感谢,问题解决了
    patx
        7
    patx  
    OP
       Feb 12, 2022
    @imn1 有局限性,因为 func1 可能是第三方包的函数。我用 patch 的 wraps 属性解决了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5384 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 01:22 · PVG 09:22 · LAX 18:22 · JFK 21:22
    ♥ Do have faith in what you're doing.