Background: I'm trying to reduce the time it takes for my tests to complete running.
I learned recently that when the Python interpreter loads a file, it executes all the code it finds therein. (Ref: https://stackoverflow.com/questions/419163/what-does-if-name-main-do)
Is there a way to prevent certain parts of the file from being executed by the interpreter ? Reason is, I have a script that creates a session and assigns that to a class attribute. The script looks something like this.
def login():
// Gets auth session from an api. This takes some seconds.
return // session
class Something(object):
class_session = login()
Now I tried to mock this login process but then, when I run my unit tests (I'm using nose btw), I think Python reads, immediately executes this script and then tries to create a session before it gets to mock the method. This takes a couple of seconds and my tests subsequently take longer to complete running (Please correct me if this is not the flow).
- Is there a way I can prevent Python from executing the script when it reads it (without wrapping the code in a function)?
- If so, what is the most Pythonic way to handle this?
- Also, how long should a well written test take to run by default. I think this should be less than 1 second (Not sure where I got that impression from tho).
Please share some insights, thanks.