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
847 views
in Technique[技术] by (71.8m points)

unit testing - How to patch a constant in python

I have two different modules in my project. One is a config file which contains

LOGGING_ACTIVATED = False

This constant is used in the second module (lets call it main) like the following:

if LOGGING_ACTIVATED:
    amqp_connector = Connector()

In my test class for the main module i would like to patch this constant with the value

True

Unfortunately the following doesn't work

@patch("config.LOGGING_ACTIVATED", True)

nor does this work:

@patch.object("config.LOGGING_ACTIVATED", True)

Does anybody know how to patch a constant from different modules?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If the if LOGGING_ACTIVATED: test happens at the module level, you need to make sure that that module is not yet imported first. Module-level code runs just once (the first time the module is imported anywhere), you cannot test code that won't run again.

If the test is in a function, note that the global name used is LOGGING_ACTIVATED, not config.LOGGING_ACTIVATED. As such you need to patch out main.LOGGING_ACTIVATED here:

@patch("main.LOGGING_ACTIVATED", True)

as that's the actual reference you wanted to replace.

Also see the Where to patch section of the mock documentation.

You should consider refactoring module-level code to something more testable. Although you can force a reload of module code by deleting the module object from the sys.modules mapping, it is plain cleaner to move code you want to be testable into a function.

So if your code now looks something like this:

if LOGGING_ACTIVATED:
    amqp_connector = Connector()

consider using a function instead:

def main():
    global amqp_connector
    if LOGGING_ACTIVATED:
        amqp_connector = Connector()

main()

or produce an object with attributes even.


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

...