Home > Software engineering >  Python - Pass a variable in a module to a function in another module
Python - Pass a variable in a module to a function in another module

Time:10-18

I have some code in multiple files like so:

A main module:

import TC1
import TC2

Some test case modules, which look like:

testcase = "Test Case 1"
successmessage = "Specific Success Message for Test Case 1"
errormessage = "Specific Error Message for Test Case 1"

# Run test
if pageLoaded == pageExpected:
    testresult = 0
    logresults()
else:
    testresult = 1
    logresults()

And a log results module:

def logresults():
    print("Test Results for", testcase,)
        if testresult == 0
            print(testcase, "Passed with", successmessage)
        else:
            print(testcase, "Failed with", errormessage)

How can I pass variables from each test case to logresults, and have it print the results of each test case as it is run?

CodePudding user response:

I see two issues with your code.

First, if you import a module with a function that works on globals, it will search for globals that share a namespace. For example, if you have a logresultsmodule with a function logresults and you import it, it will only run on variables that look like this: logresultsmodule.variable

To fix this problem, you will have to change the signature of the function to

def logresults(testresult, testcase, successmessage, errormessage): ...

and pass the corresponding variables.

The second problem is you call logresults inside a conditional where there is a chance that the testresult variable hasn't been defined yet.

First evaluate the conditional, and then call logresults.

from logresultsmodule import logresults
{code that defines testcase, successmessage, errormessage}

if pageLoaded == pageExpected: 
    testresult = 0
else:
    testresult = 1
logresults(testresult, testcase, successmessage, errormessage)

So now whenever you import a testcase, the code will run automatically and print the result message.

  • Related