Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

unit testing - Python: mock or patch a class with code executed in class initialization

I have two files, says 'example.py' and 'test.py'

The example.py is like:

  class Example(object):
    print('hello world')

    def greeting(self, words):
        print(words)

and example.py is imported in test.py :

import example

This will cause code 'print('hello world') to be executed.

Is there a way in unittest.mock to mock() or patch() class Example to stop print('hello world') being executed but still to keep method greeting() working?

question from:https://stackoverflow.com/questions/65902043/python-mock-or-patch-a-class-with-code-executed-in-class-initialization

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am sorry but I do not have enough reputation to write a comment so I have to resort to writing an answer.

For the very case that you present I believe that just suppressing the sys.stdout upon initialization is feasible. However I think that only the end result of the "print('hello world')" can be suppressed, not the execution itself.

I do not have evidence of it but I think that unittest.mocks does workarounds the "object" "class Example"(likely inspects for attributes and "copies" them dynamically). Because of this, it requires the "class Example" object to exist before actually creating the mock. Therefore the initialization of "class Example" would have already taken place and the code that you are interested in supressing would have already been executed.

Are you only interested in supressing the outcome of that code or just the execution itself ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...